Kotlin Type Checking and Smart Cast with Examples

 



Type Checking in Kotlin

  • For certain scenarios, we need to check the type of the object i.e. we need to identify the class of the object before executing any function on that object.
  • Consider a scenario where you have different types of objects in an array. You are looping on that array and executing some functionality. If you call a method that does not exist in the object, an error will be thrown at the runtime.
  • To prevent such errors, we do type checking. In Kotlin, we have an "is operator" that helps in checking the type of the object.

fun main() {
    var p1 = Person()
    if(p1 is Person) // Use of is operator
    {
        p1.sayHi()
    }
}

class Person{
    fun sayHi() = println("Hi")
}

Explanation - 

  • Here, we are checking the type of p1 instance that if it is of type Person - call its sayHi() method.
  • In this case, it is evident that the object is of type Person only but for scenarios where we need to check the type - we use an "is operator".

Smart Casting

  • Kotlin is smart - we do not have to explicitly cast i.e. whenever we use is operator, Kotlin does the smart casting for us. It infers the type of the instance and behaves according to the object. Let's understand this with an example - 
fun main() {
    var arr = arrayOf(Person(), Circle())
    for(obj in arr)
    {
        if(obj is Person)
        {
            obj.sayHi() // This obj behaves like Person object
        }
    }
}

class Person{
    fun sayHi() = println("Hi")
}

class Circle{}

Explanation

  • Here, inside the highlighted if block - obj is treated as Person object because Kotlin's compiler knows that code inside this if block will only be executed if obj is of type Person.
  • If you write this code inside Android Studio or Intelli J, autocompletion will show the methods and properties of the Person class.
  • This is known as Smart Casting as it is smartly done by Kotlin's compiler :) 

Explicit Casting

  • When you explicitly want to cast an object to a particular type - you can do so by using "as operator" in Kotlin.
if(obj is Person)
{
    obj.sayHi() 
}
else
{
    (obj as Circle).toString()
}

Explanation - 

  • Highlighted portion in the above code shows the way to explicitly cast the object to Circle. If we are sure that this is going to be a Circle object then we can use this operator.
  • We have to be careful while using explicitly casting the object using as operator as it can throw ClassCastException 

That's it for this article. For more articles on Kotlin Tutorials For Beginner Series - refer to this.

Happy Learning !! Cheers From CheezyCode.

Comments

Popular posts from this blog

Just Maths - Views, View Groups and Layouts

Create Android Apps - Getting Started