vendredi 25 septembre 2015

Scala weird behavior for type conversion in generic function

Could anyone explain why that happens?

scala> def as[T](v: Any) = Try(v.asInstanceOf[T])
as: [T](v: Any)scala.util.Try[T]

scala> as[Int]("Hello")
res0: scala.util.Try[Int] = Success(Hello)

scala> res0.map(_ + 1)
res1: scala.util.Try[Int] = Failure(java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer)

It's not about boxing because you could use your own type instead of Int and it behaves the same way.

Doesn't seem to be about by-name parameter either, because you could replace Try with Option and it will be the same.

I'm guessing it's about erasure, but maybe somebody could give a detailed explanation?





Aucun commentaire:

Enregistrer un commentaire