Actually there's nothing wrong with type inference here, type inference here means that the compiler should figure out that the T
type parameter is Int
, and the returned value from your method expression is an integer, and that's working properly:
x1: Int = 0 // this is the result of your first line
You can also try printing this:
println(x1.getClass) // int
What's not working as expected is implicit resolution for a generic type "ClassTag[_]"
. The reason it prints Nothing
is that the compiler found the object scala.reflect.ClassTag.Nothing : ClassTag[Nothing]
suitable for your case. Now about this new thing, there are loads of content on SO and the internet for why this happens and how to deal with it in different cases.
Here's another piece of code to differentiate type inference
with type erasure
in your case:
def nullAs[T]: T = null.asInstanceOf[T]
val int: Int = nullAs // 0: Int
// type erasure:
case class Container[T](value: T)
implicit val charContainer: Container[Char] = Container('c')
def nullWithContainer[T](implicit container: Container[T]): T = {
println(container)
null.asInstanceOf[T]
}
val long: Long = nullWithContainer
// prints Container(c)
// 0L
Which means type inference is done correctly, but type erasure has happened, because in runtime, the type of charContainer
is Container
, not Container[Char]
.