Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the string representation of a type at runtime in Scala

Tags:

types

scala

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)
}
like image 656
Kevin Albrecht Avatar asked Oct 10 '08 07:10

Kevin Albrecht


2 Answers

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]
like image 69
Julie Avatar answered Oct 20 '22 21:10

Julie


Note: this answer is out of date!

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

like image 33
3 revs, 2 users 90% Avatar answered Oct 20 '22 21:10

3 revs, 2 users 90%