Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `isInstanceOf` work?

Tags:

scala

subtype

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 ?

like image 502
John Threepwood Avatar asked Jul 02 '12 08:07

John Threepwood


People also ask

How does Instanceof works in Java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

How does Instanceof work in TypeScript?

The Typescript instanceof is one of the operators, and it is used to determine the specific constructor, and it will be creating the object of the classes. It will call the methods with the help of instance like that if we use an interface that can be implemented and extended through the classes.

Does Instanceof work for interfaces?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.


1 Answers

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

like image 59
drexin Avatar answered Sep 23 '22 16:09

drexin