Weird compilation error with wildcard type parameters
Sorry, I cannot formulate a title (or question for that matter) to be more informative than this because I have no idea what is going on here. Why doesn't this code compile:
class Foo
class Bar[+R <: Foo] { def bar = "bar" }
class Bak(val b: Bar[_])
val bak = new Bak(new Bar[Foo])
bak.b.bar // fine
println(bak.b) // fine
bak.b // oops!
^^^ type arguments [Any] do not conform to class Bar type parameter bounds [+R <: Foo]
What is it? Why can I use a variable but not assign it to it? Does this make sense for everyone?
source to share
Covariant with type Wildcard , the compiler will set the container type res
to Any
, for example:
scala> val l: List[_] = List(123)
l: List[_] = List(123)
scala> l
res1: List[Any] = List(123)
scala> :type l
List[Any]
Like the above code, the container type List
is _
, and since it List
is covariant , so the compiler will set l
res
to List[Any]
.
And since your code snippet is R
top before Foo
, then there is a conflict between Foo
with Any
:
val res: Bar[Any] = bak.b //+R <: Foo
for this compile error to be thrown in repl , it will automatically assign the bak.b
temp res variable .
source to share