gpt4 book ai didi

scala - 为什么 asInstanceOf 不抛出 ClassCastException?

转载 作者:行者123 更新时间:2023-12-03 14:52:16 24 4
gpt4 key购买 nike

为什么 asInstanceOf 不抛出 ClassCastException ?

scala> List("a").asInstanceOf[List[Int]]
res34: List[Int] = List(a)

最佳答案

来自 scaladoc :

Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression 1.asInstanceOf[String] will throw a ClassCastException at runtime, while the expression List(1).asInstanceOf[List[String]] will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested type.



如果您尝试访问变量或映射转换,它会正确地抛出异常:
scala> List("a").asInstanceOf[List[Int]]
res0: List[Int] = List(a)

scala> res0
res1: List[Int] = List(a)

scala> res0(0)
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

List("a").map(_.asInstanceOf[Int])
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

关于scala - 为什么 asInstanceOf 不抛出 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26089390/

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