Reputation: 16142
How can i see type of the variable in Scala?
I have tried to do this like that:
val x = 10
println(type(x))
or
val x = 'Hello!'
println(x.type)
Bun unfortunately in both of these ways i have an error.
Upvotes: 2
Views: 2603
Reputation: 24892
Depending what you're trying to do, this might be sufficient
val x=10
println(x.getClass.toString)
However, this breaks down due to type erasue; Scala has more information than Java does and the above only gives you Java's view. There's a thread here with more on this theme; outcome is:
def manOf[T:Manifest](t:T):Manifest[T] = manifest[T]
println(manOf(1))
println(manOf(List(1,2,3)))
gets you
Int
scala.collection.immutable.List[Int]
wheras the .getClass.toString
method will only get you an int
and a mysterious class scala.collection.immutable.$colon$colon
Of course if you're using the REPL shell it tells you the (scala) type of things anyway:
$ scala
Welcome to Scala version 2.9.2 (OpenJDK 64-Bit Server VM, Java 1.6.0_27).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val x=10
x: Int = 10
Upvotes: 6