Code and Screenshot
Here’s an example showing how to output a generic value’s type information using TypeTag:
import scala.reflect.runtime.universe._
object Main {
def main(args: Array[String]): Unit = {
def printType[T: TypeTag](obj: T): Unit = {
println(typeOf[T])
}
val exampleList = List(1, 2, 3)
printType(exampleList) // Output: List[Int]
}
}
Output Screenshot:
What is a TypeTag and Manifests?
Type erasure difficulties in Scala are handled with TypeTag and Manifest. They provide a means of preserving type information during runtime, which comes in handy for situations like reflection and generic programming.
TypeTag:
TypeTag gives runtime access to a generic type’s type parameters. It is a component of Scala’s reflection API (scala.reflect). You may operate with types dynamically by retrieving information about a value’s or expression’s type at runtime.
Manifest:
Manifest was created before TypeTag and has a comparable function. It was a method for capturing type information at runtime in Scala versions earlier than 2.10. But TypeTag, which has additional features and is a component of Scala’s wider reflection system, has deprecated Manifest.