0

I'm coming from a long time Python background. I've always leaned heavily on the type function in Python to spit out what kind of object I'm working with.

e.g.

In[0]:    print type("Hello")
Out[0]:   >>> string

In[0]:    print type(1234)
Out[0]:   >>> int

As I make my way into Scala territory, there are times when I'm not entirely sure what kind of object I've ended up with. being able to lay down a quick print type(obj) whenever I get a little lost would be a huge help.

e.g.

println(type(myObj))  /* Whatever the scala equivalent would be */
>>> myObj: List[String] = List(Hello there, World!)
Zack Yoshyaro
  • 2,056
  • 6
  • 24
  • 46

2 Answers2

1

The Scala equivalent of this would be the getClass method (from Java) on java.lang.Object.

For instance:

scala> 1.getClass
res0: Class[Int] = int

scala> Nil.getClass
res1: Class[_ <: scala.collection.immutable.Nil.type] = class scala.collection.immutable.Nil$

scala> "hello".getClass
res2: Class[_ <: String] = class java.lang.String
Jack Leow
  • 21,945
  • 4
  • 50
  • 55
0

You can easily access high-fidelity type information using reflection as of Scala 2.10.

Make sure to add the scala-reflect JAR to your classpath beforehand.

A little helper method is useful here:

import scala.reflect.runtime.universe._
def showTypeOf[T: TypeTag](obj: T) {
  println(typeOf[T])
}

Usage:

showTypeOf(List(1, 2, 3)) // prints List[Int]
Connor Doyle
  • 1,812
  • 14
  • 22