简体   繁体   English

为什么asInstanceOf不会抛出ClassCastException?

[英]Why asInstanceOf doesn't throw a ClassCastException?

Why asInstanceOf doesn't throw a ClassCastException ? 为什么asInstanceOf不会抛出ClassCastException?

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

From the scaladoc : 来自scaladoc

Note that the success of a cast at runtime is modulo Scala's erasure semantics. 请注意,演员在运行时的成功是以Scala的擦除语义为模。 Therefore the expression 1.asInstanceOf[String] will throw a ClassCastException at runtime, while the expression List(1).asInstanceOf[List[String]] will not. 因此,表达式1.asInstanceOf [String]将在运行时抛出ClassCastException,而表达式List(1).asInstanceOf [List [String]]则不会。 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. 在后一个示例中,因为类型参数作为编译的一部分被擦除,所以不可能检查列表的内容是否是所请求的类型。

If you try to access the variable or map the conversion it correclty throws an exception: 如果您尝试访问变量或映射转换,则correclty会抛出异常:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM