scala - Creating a Class[T] from a Manifest[T] without casting -
given ev: manifest[t]
can class[t]
using ev.erasure.asinstanceof[class[t]]
. it's shame ev.erasure
alone returns static type of class[_]
.
can class[t]
manifest without casting? if not there reason why blessed scala creators have gone raw return type in erasure
method?
i understand may have negligible impact on code i've run issue in arguably non-idiomatic piece of scala code , curious more else.
no, have cast — , should so. cast potentially unsafe, depending on want returned class
instance. imagine want roll in own version of cast:
def cast[t](obj: any)(implicit m: manifest[t]) = m.erasure.asinstanceof[class[t]].cast(obj)
this dangerous — indicated unchecked asinstanceof
. why? because code runs fine such nonsense, instance:
val listint = list(1, 2, 3) val liststring = cast[list[string]](listint)
there, list[int]
typed list[string]
. , compiles , runs fine, you'll classcastexception
later in code @ unexpected line. that's why cannot directly class[t]
manifest[t]
— because unsafe.
Comments
Post a Comment