Scala 2.10 reflection: Why am I getting the same type of "List ()" for the list item and list item?

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 result:

 $ scala ScalaApplication.scala Value: List(42) Type: List() Value: 42 Type: List() 

Why is the list type the same as the list(0) ?

I would expect something similar to the behavior 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 short: Why is the type for the list and list item listed as List() ?

+4
source share
1 answer

x.args gives you arguments of the type of this type. Since they are not available at runtime, you get an empty list for the first case, and since Int has no type arguments, you also get an empty list. You can simply print the character directly.

 println(reflect.runtime.currentMirror.reflect(thing).symbol) 

It creates

 Value: List(42) class :: Value: 42 class Integer 
+4
source

Source: https://habr.com/ru/post/1434804/


All Articles