6.3. Determining the Class of an Object

Problem

Because you don’t have to explicitly declare types with Scala, you may occasionally want to print the class/type of an object to understand how Scala works, or to debug code.

Solution

When you want to learn about the types Scala is automatically assigning on your behalf, call the getClass method on the object.

For instance, when I was first trying to understand how varargs fields work, I called getClass on a method argument, and found that the class my method was receiving varied depending on the situation. Here’s the method declaration:

def printAll(numbers: Int*) {
  println("class: " + numbers.getClass)
}

Calling the printAll method with and without arguments demonstrates the two classes Scala assigns to the numbers field under the different conditions:

scala> printAll(1, 2, 3)
class scala.collection.mutable.WrappedArray$ofInt

scala> printAll()
class scala.collection.immutable.Nil$

This technique can be very useful when working with something like Scala’s XML library, so you can understand which classes you’re working with in different situations. For instance, the following example shows that the <p> tag contains one child element, which is of class scala.xml.Text:

scala> val hello = <p>Hello, world</p>
hello: scala.xml.Elem = <p>Hello, world</p>

scala> hello.child.foreach(e => println(e.getClass))
class scala.xml.Text

However, by adding a <br/> tag inside the <p> tags, there are now three child elements of two different types:

scala> val hello ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.