could explain why 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 cast java.lang.integer) it's not boxing because use own type instead of int , behaves same way.
doesn't seem by-name parameter either, because replace try option , same.
i'm guessing it's erasure, maybe give detailed explanation?
it's in scaladoc:
note success of cast @ runtime modulo scala's erasure semantics. therefore expression
1.asinstanceof[string]throwclasscastexception@ runtime, while expressionlist(1).asinstanceof[list[string]]not. in latter example, because type argument erased part of compilation not possible check whether contents of list of requested type.
so, because t erased, try(v.asinstanceof[t]) not throw classcastexception, because far jvm knows, have try[any]. try treat contained type int, trigger exception.
Comments
Post a Comment