By Alvin Alexander. Last updated: August 10, 2017
I was doing a little Scala programming this morning, and because I hadn't written any code in a while, I managed to forget how isInstanceOf works with inheritance in Scala.
To refresh my memory, I wrote the following example code:
/** * The problem with Scala isInstanceOf and inheritance. */ object Foo extends App { class Foo class Bar extends Foo class Baz extends Bar val foo = new Foo val bar = new Bar val baz = new Baz println("foo.isInstanceOf[Foo]: " + (foo.isInstanceOf[Foo])) // true println("bar.isInstanceOf[Foo]: " + (bar.isInstanceOf[Foo])) // true println("baz.isInstanceOf[Foo]: " + (baz.isInstanceOf[Foo])) // true }
As you can see, isInstanceOf
says "true" for any comparison with the current class, or any parent classes.
Note: I removed the rest of this article because it was wrong. I'll try to remember to update article when I have more time.