scala isInstanceOf
In Scala, the isInstanceOf
method is used to check whether an object is an instance of a particular class or trait. It returns true
if the object is an instance of the specified type, and false
otherwise.
Here's an example of how to use the isInstanceOf
method:
class MyClass
val obj = new MyClass
if (obj.isInstanceOf[MyClass]) {
println("obj is an instance of MyClass")
} else {
println("obj is not an instance of MyClass")
}
In this example, we define a class MyClass
and create an instance of it called obj
. We then use the isInstanceOf
method to check if obj
is an instance of MyClass
. If it is, we print "obj is an instance of MyClass", otherwise we print "obj is not an instance of MyClass".
Note that the isInstanceOf
method also works with traits and interfaces. For example:
trait MyTrait
val obj = new MyClass with MyTrait
if (obj.isInstanceOf[MyTrait]) {
println("obj is an instance of MyTrait")
} else {
println("obj is not an instance of MyTrait")
}
In this case, we define a trait MyTrait
and create an instance of MyClass
that also extends MyTrait
. We use the isInstanceOf
method to check if obj
is an instance of MyTrait
, and print the appropriate message based on the result.
Please let me know if you need any further assistance!