我对泛型类型感到困惑。我希望 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)
最佳答案
a.asInstanceOf[B]
方法:
亲爱的编译器;
请忘记您认为的类型 a
是。我知道的更好。我知道如果 a
实际上不是类型 B
然后我的程序可能会崩溃,但我真的很聪明,这不会发生。
此致, super 程序员
换句话说 val b:B = a.asInstanceOf[B]
不会创建 B
类型的新变量,它将创建一个新变量,该变量将被视为类型 B
.如果实际底层类型为a
兼容类型 B
那么一切都很好。如 a
的真实类型与 B
不兼容然后事情就炸了。
关于Scala 转换为泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60521145/