gpt4 book ai didi

Scala 2.10 反射 : Why do I get the same type "List()" for the list and list element?

转载 作者:行者123 更新时间:2023-12-01 01:15:12 26 4
gpt4 key购买 nike

使用 scala-2.10.0-M7,考虑以下 Scala 程序:

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});
}

}

它提供以下输出:
$ scala ScalaApplication.scala 
Value: List(42)
Type: List()
Value: 42
Type: List()

为什么是 list的类型与 list(0)的类型相同?

我会期望类似于以下 Java 程序的行为:
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());
}

}

这给出了结果:
$ java JavaApplication
Value: [Ljava.lang.Integer;@16675039
Type: Integer[]
Value: 42
Type: Integer

总之:
为什么列表和列表元素的类型都报告为 List() ?

最佳答案

x.args为您提供类型的类型参数。由于它们在运行时不可用,因此对于第一种情况和从 Int 起,您会得到一个空列表。没有任何类型参数,您也会在那里得到一个空列表。您可以直接打印出符号。

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

这产生
Value: List(42)
class ::
Value: 42
class Integer

关于Scala 2.10 反射 : Why do I get the same type "List()" for the list and list element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12474360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com