Search code examples
scalasubtype

How does `isInstanceOf` work?


Assume, we have:

class B
class A extends B
trait T

Then it holds:

val a: A with T = new A with T 
a.isInstanceOf[B]  // result is true !

Is it right to say, the isInstanceOf method checks, if there is at least one type (not all types) which matches the right hand side in a subtype relationship?

At first look, I thought a value with type A with T can not be a subtype of B, because A and T are not both subtypes of B. But it is A or T is a subtype of B -- is that right ?


Solution

  • isInstanceOf looks if there is a corresponding entry in the inheritance chain. The chain of A with T includes A, B and T, so a.isInstanceOf[B] must be true.

    edit:

    Actually the generated byte code calls javas instanceof, so it would be a instanceof B in java. A little more complex call like a.isInstanceOf[A with T] would be (a instanceof A) && (a instanceof T).