2

I am trying to understand my mistake in implementing generics. I have a trait which defines a method that returns a reference with an upper type bound of the trait. How ever a var reference to an implementation of the trait fails to type check with Expression of type Capability[Class] doesn't conform to expected type Capability[Trait]

Here is the code:

trait IAITask {
  def taskTypeReference[T >: IAITask]: Capability[T]
}

object Tasks {
   var Walk: Capability[Walk] = _
}

class Walk extends IAITask {
  override def taskTypeReference[T >: IAITask]: Capability[IAITask] = Tasks.Walk //This line does not type check
}

1 Answers1

1

If it's a Java interface, then you might want to try to imitate Java's use-site variance by wildcards:

trait Capability[A]

trait IAITask {
  def taskTypeReference: Capability[_ <: IAITask]
}

object Tasks {
   var Walk: Capability[Walk] = _
}

class Walk extends IAITask {
  override def taskTypeReference: Capability[_ <: IAITask] = Tasks.Walk
}
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93