Consider the following snippet:
trait X[-T]
object Y extends X[Nothing]
def a[T](x: X[T]): X[T] = x
a(Y)
Compilation of the above (2.12.3) fails with:
type mismatch;
found : Y.type
required: X[T]
a(Y)
^
This compiles fine if:
- a different type than
Nothing
is used (e.g.object Y extends X[String]
) - the method
a
doesn't useT
in its return type (e.g.def a[T](x: X[T]): Unit = {}
) - the type parameter for
a
is explicitly given (i.e.a[Nothing](Y)
) T
is covariant, not contravariant (also fails if it's invariant)
Is this some special case in the compiler for Nothing
?
As an "interesting" work-around, the following seems to work fine:
trait X[-T]
object Y extends X[Nothing]
def a[T, U <: T](x: X[T]): X[U] = x
a(Y)
String
instead ofNothing
makes the example compile? Or why does the work-around work? – Largess