Cast value from Any using ClassManifest in Scala

I have values List[Any]and a list of corresponding ClassManifest[_]s types storing values. How can I add some value from the list back to the original type?

def cast[T](x: Any, mf: ClassManifest[T]): T = x.asInstanceOf[T] does not work.

Thank you for your responses.

+3
source share
2 answers

This can never work, since the return type castwill always be considered the highest general supertype of any T. At compile time, this cannot be made more specific.

If you are trying to create 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

+3

Class Java/Scala - Class.cast. , :

mf.erasure.cast(x) //T

, mf.erasure - Class[_] ( a Class<?> Java), (.. ). () .

0

Source: https://habr.com/ru/post/1778928/


All Articles