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".