tags:

views:

516

answers:

3

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)
}
+3  A: 

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

svrist
The guys there are really nice!
svrist
it's false. see answer about manifests
Alexey
A: 

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

svrist
+2  A: 

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.