You should look at the following line as two separate parts, left side = and right:
val oB: Option[B] = collectFirstOf(List(new A,new B))
What you expect from here is that the type of the expression collectFirstOf (rvalue) should be inferred from the value type of oB. The compiler cannot do this. You have to say specifically what type you expect. Take the following example:
val v: Long = 1 + 4
The expression type 1 + 4 is Int. Then this int is converted to Long. The compiler does not and cannot conclude that you want 1 or 4 to be long:
So, to fix your problem, you need to tell the compiler what type you expect, otherwise it assumes java.lang.Object:
val oB = collectFirstOf[B](List(new A,new B))
So, the manifest is correctly assigned, and everything is fine with the world. So why does the following compile:
val oB:Option[B] = collectFirstOfT(List(new A,new B)) oB: Option[B] = Some( A@10f3a9c )
at first glance, it seems that this should not work, but it is. This is because collectFirstOfT actually returns the [Nothing] parameter, which can be safely converted to the [B] option:
scala> val f = collectFirstOfT(List(new A,new B)) f: Option[Nothing] = Some( A@baecb8 ) scala> f.asInstanceOf[Option[B]] res4: Option[B] = Some( A@baecb8 )
source share