parsa
parsa

Reputation: 2668

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      
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).

Upvotes: 1

Views: 2562

Answers (2)

mythicalprogrammer
mythicalprogrammer

Reputation: 4737

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.

Upvotes: 6

nfechner
nfechner

Reputation: 17525

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

Upvotes: 4

Related Questions