How to check "instanceof" class in Kotlin?


Kotlin is a cross-platform, statistically typed, general-purpose programming language. It is very popular among the developer community because of its interoperable nature with JVM. In the programming world sometimes it is required to check the type of an object to implement a business logic.

Unlike Java, we don't have an "instance of" operator in Kotlin. However, we have an "is" operator in Kotlin for type checking and casting.

Example

The following example demonstrates how the "is" operator works in Kotlin.

fun main(args: Array<String>) {
   val x: String = "TutorialsPoint"
   // checking the instance and matching the type
   if(x is String){
      println("The entered value is string")
   }
   else{
      println("Invalid inputs ")
   }
}

Output

It will match whether the value of variable "x" is a String or not and depending on that, it will generate the following output.

The entered value is string

We also have a "negate instance of" operator which is "!is". The following example shows how to use it.

fun main(args: Array<String>) {
   val x: String = "TutorialsPoint"
   if(x !is String){
      println("The entered value is string")
   }
   else{
      println("Invalid inputs ")
   }
}

Output

"!is" will check whether the value of "x" is a String or not and depending on that, it will generate following output:

Invalid inputs

Updated on: 23-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements