Let's have a hierarchy defined like this:
trait Upper
case class Error(msg: String) extends Upper
Trying to define a trait like this:
trait Mixin[T <: Upper] {
def compute[S <: T](param: String, obj: S)
def use = compute("hello", Error("world"))
}
Causes compilation error:
error: inferred type arguments [Error] do not conform to method compute's type parameter bounds [S <: T]
def use = compute("hello", Error("world"))
^
error: type mismatch;
found : Error
required: S
def use = compute("hello", Error("world"))
^
Can someone explain me why that happens, and how to workaround it?
Update
The type bounds can't be removed. They are necessary because of some implicits that won't work otherwise.
I'm not sure what you're trying to do with this, but the type parameter
T
onMixin
is an invariant with an upper-bound ofUpper
. That means that we know it is some sub-type ofUpper
, but we don't know which--which means we don't know that it has typeError
. And we can't know thatError
is a sub-type ofT
.If you introduce a third type
case class A extends Upper
, it becomes more clear why this can't work.T
might beA
, and ifS <: A
, thenS = Error <: T = A
is impossible.How can you work around this? Remove the type bounds. It's not clear why you have them in the first place.