Scala 转换为泛型类型

标签 scala casting type-erasure boxing

我对泛型类型感到困惑。我希望 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/

相关文章:

multithreading - 更换池中表现不佳的 worker

javascript - 如何进行运行时转换

java - 为什么三元运算符会意外地转换整数?

java - DWR 如何转换传入数据并规避类型删除

Java 泛型 : Instantiating arrays with parameterized types: illegal?

c++ - 像 std::function 这样的自毁类型删除类是如何实现的?

scala - 玩框架 Atmosphere

java.lang.NoClassDefFoundError : scala/StringContext

scala - lambdas 在 Scala 中是如何工作的,它们是在匿名类之上运行的吗?

Java - 带返回值的异步方法