Reputation: 41909
Given:
scala> def f[A]: Unit = ???
f: [A]=> Unit
I'd like to replace the definition to print out A
's type.
Is there any alternative to:
scala> def f[A](implicit manifest: scala.reflect.Manifest[A]) = manifest.toString
f: [A](implicit manifest: scala.reflect.Manifest[A])String
scala> f[String]
res10: String = java.lang.String
Upvotes: 3
Views: 1823
Reputation: 55569
That isn't actually printing out the type, it's printing out the class.
scala> f[List[Int]]
res17: String = scala.collection.immutable.List[Int]
Use a TypeTag
to get the type information. But no, there isn't a simpler way. Since this is happening at runtime, you need the TypeTag
to hold the type information.
scala> import scala.reflect.runtime.universe.{TypeTag, typeOf}
import scala.reflect.runtime.universe.{TypeTag, typeOf}
scala> def f[A](implicit tt: TypeTag[A]): Unit = println(typeOf[A])
f: [A](implicit tt: reflect.runtime.universe.TypeTag[A])Unit
scala> f[List[Int]]
scala.List[Int]
We can make it look more concise with the context bound syntax:
def f[A : TypeTag]: Unit = println(typeOf[A])
Upvotes: 12