Scala: downcasting throws java.lang.ClassCastException
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 开发者_StackOverflow社区
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).
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.
You cant cast A
into B
, only the other way around, because B is more specific than A.
精彩评论