In Java, we use the instanceOf operator to check if an object is an instance of a certain class or interface? In Kotlin, we will use the is operator!
For example, I have an interface with 2 implementations as follows:
1 2 3 4 |
package com.huongdankotlin interface Shape { } |
1 2 3 4 |
package com.huongdankotlin class Triangle : Shape { } |
1 2 3 4 |
package com.huongdankotlin class Rectangle : Shape { } |
Now, if I instantiate a new Shape object with the implementation of Triangle, when checking if this new object is an instance of Rectangle using the is operator:
1 2 3 4 5 6 7 8 9 |
package com.huongdankotlin fun main() { var shape: Shape shape = Triangle() println(shape is Rectangle) } |
you will see the following result:
Conversely, to check that this object is not an instance of the Rectangle class, you can declare “!is” as follows:
1 2 3 4 5 6 7 8 9 |
package com.huongdankotlin fun main() { var shape: Shape shape = Triangle() println(shape !is Rectangle) } |
Result: