【发布时间】:2020-06-16 15:44:07
【问题描述】:
我对泛型类型感到困惑。我希望2.asInstanceOf[A] 被转换为A 类型,同时它被转换为Int。
除此之外,输入是java.lang.Long,而输出是Int 的列表(根据定义,输入和输出应该是相同的类型)。这是为什么呢?
def whatever[A](x: A): List[A] = {
val two = 2.asInstanceOf[A]
val l = List(1.asInstanceOf[A],2.asInstanceOf[A])
println(f"Input type inside the function for 15L: ${x.getClass}")
println(f"The class of two: ${two.getClass}, the value of two: $two")
println(f"The class of the first element of l: ${l.head.getClass}, first element value: ${l.head}")
l
}
println(f"Returned from whatever function: ${whatever(15L)}")
输出:
Input type inside the function for 15L: class java.lang.Long
The class of two: class java.lang.Integer, the value of two: 2
The class of the first element of l: class java.lang.Integer, first element value: 1
Returned from whatever function: List(1, 2)
【问题讨论】:
标签: scala casting type-erasure boxing