Scala:向下转型抛出 java.lang.ClassCastException

发布于 2024-11-19 19:04:57 字数 647 浏览 5 评论 0原文

从非 Java 背景转向 Scala 给我带来了很多困难,包括这个。

scala> class A
defined class A

scala> class B extends A      
defined class B

scala> val a = new A
a: A = A@2e893a4a

scala> val b = new B
b: B = B@3a47c130

scala> a.asInstanceOf[B]
java.lang.ClassCastException: A cannot be cast to B
...

scala> b.asInstanceOf[A]
res1: A = B@3a47c130

我知道抛出 ClassCastException 是因为在运行时, a 看起来不像 B,但事实上,它是(据我所知)。这是怎么回事?有什么解决方法吗?谢谢。

编辑:JVM 如何理解 a 无法转换为 B?它是否在 a.getClassB 之间执行一些浅层比较?

附注我试图将私有变量添加到库类中,并重写接受库中定义的类作为参数的类方法之一(我试图将字段添加到的类)。

Coming from a non-Java background to Scala has brought me a wide range of difficulties including this one.

scala> class A
defined class A

scala> class B extends A      
defined class B

scala> val a = new A
a: A = A@2e893a4a

scala> val b = new B
b: B = B@3a47c130

scala> a.asInstanceOf[B]
java.lang.ClassCastException: A cannot be cast to B
...

scala> b.asInstanceOf[A]
res1: A = B@3a47c130

I understand that ClassCastException is thrown because at runtime, a doesn't seem like a B but in fact, it is (as far as I understand). What's going on here? Any workarounds? Thanks.

Edit: how does the JVM understand that a cannot be casted to B? Does it perform some shallow comparison between a.getClass and B?

ps. I'm trying to add a private variable to a library class, and override one of the class methods that accepts a class defined in the library as argument (the class I'm trying to add the field to).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

掩饰不了的爱 2024-11-26 19:04:57

这是一个向下的层次结构。 A 类是一个超类,B 类从它扩展而来,因此它更具体。你无法笼统地提升层次结构。这是一种设计选择,与子类型相关。

有没有一种语言可以提升层次结构?因为你似乎在暗示存在这样一种语言。

It's a hierarchy that goes down. Class A is a super class and B extends from it so it's more specific. You cannot go up the hierarchy in generalization. It's a design choice and relates to subtyping.

Is there any language where you can go up the hierarchy? Cause it seems like you're implying that there is such a language.

淤浪 2024-11-26 19:04:57

您不能将 A 转换为 B,只能反过来,因为 B 比 A 更具体。

You cant cast A into B, only the other way around, because B is more specific than A.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文