Scala 转换为泛型类型

Syl*_*cka 4 boxing casting scala type-erasure

我对泛型类型感到困惑。我希望它2.asInstanceOf[A]被转换为 type 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)}")

Run Code Online (Sandbox Code Playgroud)

输出:

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)
Run Code Online (Sandbox Code Playgroud)

jwv*_*wvh 15

a.asInstanceOf[B] 方法:

亲爱的编译器;

请忘记你认为的类型a是什么。我知道的更好。我知道如果a不是真的打字,B那么我的程序可能会崩溃,但我真的很聪明,这不会发生。

此致,超级程序员

换句话说val b:B = a.asInstanceOf[B]不会创建类型的新变量B,它会创建一个将被视为一个新的变量,就好像它是类型B。如果实际的底层类型a与类型兼容,B那么一切都很好。如果a的真实类型与不兼容,B那么事情就会爆炸。

  • 这种答案让我希望自己能投不止一票:) (4认同)