Open In App

How to Type Check an Object in Kotlin?

Improve
Improve
Like Article
Like
Save
Share
Report

Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a “better language” than Java, but still be fully interoperable with Java code. In this article, we are going to discuss how to type-check an object in Kotlin, before moving further you should know some basics as Kotlin basics. One often needs to check if an object is of a particular type at runtime. With Java, we used an instance of a keyword; with Kotlin, it is the ‘is‘ keyword.

Example

Let’s see how to type-check an object in these steps:

1. Let’s try a very basic example, trying is with string and integer

In this example, we will type-check a string and an integer:

Kotlin




fun main (args: Array<String>) {
  var a : Any = 1
  var b : Any = "1"
  if (a is String)
  println ("a = $a is String")
  else 
        println ("a = $a is not String")
   if (b is String)
        println ("b = $b is String")
   else 
     println ("b = $b is not String")
 }


Output:

a = 1 is not String
b = 1 is String

2. Similarly, we can use “!is” to check whether the object is not of type String, like this:

Kotlin




fun main (args: Array<String>) {
  var b : Any = 1
  if (b !is String) 
    println ("$b is not string")
  else 
    println ("$b is String")
}


Output:

1 is not string

If you remember how when works in Kotlin, we do not need to put in the is the keyword, because Kotlin has a feature of the smart cast and throws an error if the compared objects are not of the same type.

Basically, the is operator is used to check the type of the object in Kotlin, and “!is” is the negation of the “is” operator. Kotlin compiler tracks immutable values and safely casts them wherever needed. This is how smart casts work; “is” is a safe cast operator, whereas an unsafe cast operator is the as operator.

Let’s try an example with the “as” operator, which is used for casting in Kotlin. It is an unsafe cast operator. The following code example throws ClassCastException because we cannot convert an integer to String:

Kotlin




fun main (args: Array<String>) {
  var a : Any = 1
  var b = a as String
}


Output:

ERROR

On the other hand, the following code runs successfully because of variable a, which, being of Any type, can be cast to String:

Kotlin




fun main (args: Array<String>) {
  var a : Any = "1"
  var b = a as String
  println (b. length)
}


Output:

1


Last Updated : 25 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads