Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created April 25, 2019 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debasishg/738436be246179293c50f4ab7bef02b1 to your computer and use it in GitHub Desktop.
Save debasishg/738436be246179293c50f4ab7bef02b1 to your computer and use it in GitHub Desktop.
Getting runtime types in Scala
Can we do it with `ClassTag` ?
Adriaan:
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]]
TypeTag[Either[Int,String]]
Adriaan:
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)
(Int,java.lang.String)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment