I've got a List[Any] of values and a list of corresponding ClassManifest[_]s, storing values' original types. 开发者_运维百科How do i cast some value from list back to it's original type?
def cast[T](x: Any, mf: ClassManifest[T]): T = x.asInstanceOf[T] doesn't work.
Thank You for your answers.
That can't ever possibly work, as the return type of cast will always be taken as the highest common supertype of whatever T is restricted to. There's no way it can be made any more specific at compile time.
If you're trying to build a strongly-typed collection of disparate types, then what you really want is an HList:
http://jnordenberg.blogspot.com/2008/09/hlist-in-scala-revisited-or-scala.html
The way to use a Class instance in Java/Scala to cast an object is to use the Class.cast method. So you may think that you could do:
mf.erasure.cast(x) //T
But this will not work, because mf.erasure is a Class[_] (or a Class<?> in Java), so the cast is meaningless (i.e. offers no extra information). This is (of course) one of the drawbacks in using non-reified generics.
加载中,请稍侯......
精彩评论