Scala equivalent of Java .class (classOf)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shorter recipes, Recipe 6.2, “The Scala equivalent of Java’s .class.”

Problem

When an API requires that you pass in a Class, you’d call .class on an object in Java, but that doesn’t work in Scala.

Solution

Use the Scala classOf method instead of Java’s .class. The following example shows how to pass a class of type TargetDataLine to a method named DataLine.Info:

val info = new DataLine.Info(classOf[TargetDataLine], null)

By contrast, the same method call would be made like this in Java:

// java
info = new DataLine.Info(TargetDataLine.class, null);

The classOf method is defined in the Scala Predef object and is therefore available in all classes without requiring an import.

Discussion

This approach also lets you begin with simple reflection techniques. The following REPL example demonstrates how to access the methods of the String class:

scala> val stringClass = classOf[String]
stringClass: Class[String] = class java.lang.String

scala> stringClass.getMethods
res0: Array[java.lang.reflect.Method] = Array(public boolean java.lang.String.equals(java.lang.Object), public java.lang.String
(output goes on for a while ...)

See Also

  • Oracle’s “Retrieving Class Objects” document
  • The Scala Predef object