3

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.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
fehu
  • 457
  • 2
  • 8
  • Your question is quite similra to : http://stackoverflow.com/questions/1094173/how-do-i-get-around-type-erasure-on-scala-or-why-cant-i-get-the-type-parameter – Nicolas Dec 07 '10 at 12:24

2 Answers2

3

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

Kevin Wright
  • 49,540
  • 9
  • 105
  • 155
  • Thx, it looks interesting, but am i correct that for now HList is limited by 10 elements? – fehu Dec 07 '10 at 14:34
  • @fehu: Why would you think that? One of the motivations for an HList is that it can hold an arbitrary number of elements, exceeding the 22-element limit of a Tuple. – Kevin Wright Dec 07 '10 at 15:08
0

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.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449