Reputation: 848
In Scala, during type erasure, the generic variable is replaced by 'Object' type wherever the generic variable appears in type position.
E.G: val x T;
--> is replaced by val x Object;
Due to this, the details of exact type which is passed, will become unavailable during runtime.
To overcome this (to get the exact type during runtime), it is mentioned that ClassTag will help us.
Can you please help me how ClassTag gets the type information during runtime ?
When ClassTag is mentioned , that is also written with a generic type in context bound.
E.G: def method[T:ClassTag] {...}
So I think, the 'T' mentioned here too, will be erased. But ClassTag somehow keeps the type info. I am bit puzzled how this works.. (similarly TypeTag and WeakTag as well)
Upvotes: 0
Views: 833
Reputation: 27356
This is not correct:
E.G: val x T; --> is replaced by val x Object;
The type of x
is not lost; you can look at the value of x
at runtime and determine what type it is. Objects retain their runtime type.
Type erasure affects values of a parameterised type Y[T]
. The runtime holds a single type for an object so it cannot hold T
as well as Y
and "erases" T
from the type. If I have an instance of Y[T]
I can tell at runtime that it is type Y
but cannot tell which T
it was parameterised with.
Thus I can distinguish List[T]
from Vector[T]
but cannot distinguish List[T]
from List[U]
. But an element of that List
retains its type and can be matched against T
or U
. And a member val x: T
can be matched directly to determine the type of the object.
A ClassTag
is value that represents a type, so if you store the ClassTag
of T
in your object then you can match that to work out the type of T
without having to look at any of the values of type T
inside the object. You are explicitly storing the type information for T
that was previously erased.
[ Useful discussion in the comments about this really being about classes rather than types ]
Upvotes: 3