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)
This is not correct:
The type of
x
is not lost; you can look at the value ofx
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 holdT
as well asY
and "erases"T
from the type. If I have an instance ofY[T]
I can tell at runtime that it is typeY
but cannot tell whichT
it was parameterised with. Thus I can distinguishList[T]
fromVector[T]
but cannot distinguishList[T]
fromList[U]
. But an element of thatList
retains its type and can be matched againstT
orU
. And a memberval 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 theClassTag
ofT
in your object then you can match that to work out the type ofT
without having to look at any of the values of typeT
inside the object. You are explicitly storing the type information forT
that was previously erased.[ Useful discussion in the comments about this really being about classes rather than types ]