Using scala-2.10.0-M7, consider the following Scala program:
import reflect.runtime.universe._
object ScalaApplication {
def main(args: Array[String]) {
val list = List(42)
printValueAndType(list)
printValueAndType(list(0))
}
def printValueAndType (thing: Any) {
println("Value: " + thing)
println(reflect.runtime.currentMirror.reflect(thing).symbol.toType match {case x:TypeRef => "Type: " + x.args});
}
}
It gives the following output:
$ scala ScalaApplication.scala
Value: List(42)
Type: List()
Value: 42
Type: List()
Why is the type of list the same as the type of list(0)?
I would have expected something similar to the behaviour of the following Java program:
public class JavaApplication {
public static void main(String[] args) {
Integer[] list = new Integer[]{42};
printValueAndType(list);
printValueAndType(list[0]);
}
public static void printValueAndType(Object o) {
System.out.println("Value: " + o.toString());
System.out.println("Type: " + o.getClass().getSimpleName());
}
}
Which gives the result:
$ java JavaApplication
Value: [Ljava.lang.Integer;@16675039
Type: Integer[]
Value: 42
Type: Integer
In summary:
Why is the type for both the list and the list element reported as List()?
x.argsgives you the type arguments of the type. Since they aren’t available at runtime, you get an empty list for the first case and sinceIntdoes not have any type arguments, you get an empty list there as well. You can just print out the symbol directly.This produces