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
xis not lost; you can look at the value ofxat 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 holdTas well asYand "erases"Tfrom the type. If I have an instance ofY[T]I can tell at runtime that it is typeYbut cannot tell whichTit was parameterised with. Thus I can distinguishList[T]fromVector[T]but cannot distinguishList[T]fromList[U]. But an element of thatListretains its type and can be matched againstTorU. And a memberval x: Tcan be matched directly to determine the type of the object.A
ClassTagis value that represents a type, so if you store theClassTagofTin your object then you can match that to work out the type ofTwithout having to look at any of the values of typeTinside the object. You are explicitly storing the type information forTthat was previously erased.[ Useful discussion in the comments about this really being about classes rather than types ]