Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Getting runtime types in Scala
Can we do it with `ClassTag` ?
You can't with a class tag, as it represents the erased type as known to the JVM. You could use a TypeTag
to reify the full type, but that depends on full scala reflection, which has its own downsides
(not thread safe, basically pulls in the compiler,...)
scala> import scala.reflect.runtime.universe.TypeTag
import scala.reflect.runtime.universe.TypeTag
scala> def myMethod[T: TypeTag] = println(implicitly[TypeTag[T]])
myMethod: [T](implicit evidence$1: reflect.runtime.universe.TypeTag[T])Unit
scala> myMethod[Either[Int, String]]
again, I wouldn't exactly recommend this -- probably best to capture the type arguments to Either
directly using a ClassTag
scala> def whatsmyEither[T: reflect.ClassTag, U: reflect.ClassTag](either: Either[T, U]) = println((reflect.classTag[T], reflect.classTag[U]))
whatsmyEither: [T, U](either: Either[T,U])(implicit evidence$1: scala.reflect.ClassTag[T], implicit evidence$2: scala.reflect.ClassTag[U])Unit
scala> val x: Either[Int, String] = null
x: Either[Int,String] = null
scala> whatsmyEither(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment