Kevin Albrecht
Kevin Albrecht

Reputation: 7014

Getting the string representation of a type at runtime in 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)
}

Upvotes: 11

Views: 7577

Answers (4)

svrist
svrist

Reputation: 7110

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

Upvotes: 6

Julie
Julie

Reputation: 6209

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]

Upvotes: 10

Alex Cruise
Alex Cruise

Reputation:

There's a new, mostly-undocumented feature called "manifests" in Scala; it works like this:

object Foo {
  def apply[T <: AnyRef](t: T)(implicit m: scala.reflect.Manifest[T]) = println("t was " + t.toString + " of class " + t.getClass.getName() + ", erased from " + m.erasure)
}

The AnyRef bound is just there to ensure the value has a .toString method.

Upvotes: 6

svrist
svrist

Reputation: 7110

Please note that this isn't really "the thing:"

object Test {
    def main (args : Array[String]) {
    println(classOf[List[String]])
    }
}

gives

$ scala Test                    
class scala.List

I think you can blame this on erasure

====EDIT==== I've tried doing it with a method with a generic type parameter:

object TestSv {
  def main(args:Array[String]){
    narf[String]
  }
  def narf[T](){
    println(classOf[T])
  }
}

And the compiler wont accept it. Types arn't classes is the explanation

Upvotes: 2

Related Questions