Scala type bounds "single-levelness"

58 views Asked by At

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.

1

There are 1 answers

1
Michael Zajac On

I'm not sure what you're trying to do with this, but the type parameter T on Mixin is an invariant with an upper-bound of Upper. That means that we know it is some sub-type of Upper, but we don't know which--which means we don't know that it has type Error. And we can't know that Error is a sub-type of T.

If you introduce a third type case class A extends Upper, it becomes more clear why this can't work.

T might be A, and if S <: A, then S = 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.