A Tour of Scala: Predefined function classOf

 The predefined function classOf[T] returns a runtime representation of the Scala class type T. The following Scala code example prints out the runtime representation of the args parameter:

object ClassReprTest {
  abstract class Bar {
    type T <: AnyRef
    def bar(x: T) {
      println("5: " + x.getClass())
    }
  }
  def main(args: Array[String]) {
    println("1: " + args.getClass())
    println("2: " + classOf[Array[String]])
    new Bar {
      type T = Array[String]
      val x: T = args
      println("3: " + x.getClass())
      println("4: " + classOf[T])
    }.bar(args)
  }
}

Here is the output of the Scala program:

1: class [Ljava.lang.String;
2: class [Ljava.lang.String;
3: class [Ljava.lang.String;
4: class [Ljava.lang.String;
5: class [Ljava.lang.String;

A similar code example in Java 5 (aka. JDK 1.5) looks as follows:

When you execute the above Java program it will display four times the string "class [Ljava.lang.String;".

 

Copyright © 2010 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland