In Scala, is it possible to get the string representation of a type at runtime? I am trying to do something along these lines:
def printTheNameOfThisType[T]() = {
println(T.toString)
}
In Scala 2.10 and above, use TypeTag
, which contains full type information. You'll need to include the scala-reflect
library in order to do this:
import scala.reflect.runtime.universe._
def printTheNameOfThisType[T: TypeTag]() = {
println(typeOf[T].toString)
}
You will get results like the following:
scala> printTheNameOfThisType[Int]
Int
scala> printTheNameOfThisType[String]
String
scala> printTheNameOfThisType[List[Int]]
scala.List[Int]
Please see answer using TypeTag for Scala 2.10 and above
May I recommend #Scala on freenode
10:48 <seet_> http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible?
10:48 <seet_> possible
10:48 <lambdabot> Title: Getting the string representation of a type at runtime in Scala - Stack Overflow,
http://tinyurl.com/53242l
10:49 <mapreduce> Types aren't objects.
10:49 <mapreduce> or values
10:49 <mapreduce> println(classOf[T]) should give you something, but probably not what you want.
Description of classOf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With