I want to get the type of a variable at runtime. How do I do this?
This question is related to
scala
reflection
i have tested that and it worked
val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}
I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:
If you wish to print as you have specified then:
scala> def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]
scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)
scala> println(manOf(x))
scala.collection.immutable.List[Int]
If you are in repl mode then
scala> :type List(1,2,3)
List[Int]
Or if you just wish to know what the class type then as @monkjack explains "string".getClass
might solve the purpose
If by the type of a variable you mean the runtime class of the object that the variable points to, then you can get this through the class reference that all objects have.
val name = "sam";
name: java.lang.String = sam
name.getClass
res0: java.lang.Class[_] = class java.lang.String
If you however mean the type that the variable was declared as, then you cannot get that. Eg, if you say
val name: Object = "sam"
then you will still get a String
back from the above code.
Source: Stackoverflow.com