scalatypeclassimplicittype-parametercontext-bound

Typeclasses methods called in functions with type parameters


I'm trying to use a typeclass method inside a function with a type parameter. Unfortunately I can't get it to work.

When I try to use the method addRegisterInOut the compiler throws an error on the following code.

class Module extends Component {

  // ...

  trait HasDataSpecs[T] {
    def dataSpecs(datatype: T) : RegisterSpecs
  }

  implicit object SpecsBool extends HasDataSpecs[Bool] {
    override def dataSpecs(datatype: Bool) : RegisterSpecs = {
    new RegisterSpecs("", 1)}
  }

  implicit object SpecsUInt extends HasDataSpecs[UInt] {
    override def dataSpecs(datatype: UInt) : RegisterSpecs = {
    new RegisterSpecs("", datatype.getBitsWidth)}
  }


  def dataSpecs[A](a: A)(implicit ds: HasDataSpecs[A]) : RegisterSpecs = ds.dataSpecs(a)

// ...

  def addRegisterInOut[T <: Data](name: String, out_data: T) : T = {
    var specs = dataSpecs(out_data)
    specs.name = name
    specs.permission = Permission.RWPerm
    registers += specs
    out_len += out_data.getBitsWidth
    in_len += out_data.getBitsWidth
    val in_data = cloneOf(out_data)
    in_channels += in_data
    out_channels += out_data
    in_data
  }

}


//... Somewhere I use addRegisterInOut(UInt(...))

I get

[error] /home/bellandi/Projects/VHDL/spinalhdl_experiments/src/main/scala/spinal/msk/lib/pkg/RegisterCls.scala:83:26: could not find implicit value for parameter ds: Module.this.HasDataSpecs[T]
[error]     var specs = dataSpecs(out_data)
[error]                          ^

I would expect the compiler to halt only on types where an implicit is not defined, but it seems to happen always.


Solution

  • Try to add context bound

    def addRegisterInOut[T <: Data : HasDataSpecs](name: String, out_data: T) : T = ...