Open In App

What is a TypeTag and Manifests?

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Code and Screenshot

Here’s an example showing how to output a generic value’s type information using TypeTag:

Scala
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:

Screenshot-(364)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads