Kotlin | Type Checking and Smart Casting
Type Checking –
In Kotlin, we can check the type of certain variable using the is operator at runtime. It is a way of checking the type of a variable at runtime to separate the flow for different objects. Kotlin program of type checking using if-else blocks-
Name: Praveen Age: 24 Salary: 5000.55
Explanation: Here, we initialize three variables name, age and salary then passes into the list. Then, traverse the list with help of for loop, in each if-else block we check the type of the element using is operator and execute the respective print() statement. Using when expression – We can easily replace the if-else blocks with when expression. We have already learnt about when expression in control flow articles. For more details, we can refer when expression in Kotlin. Kotlin program of type checking using when –
Name: Praveen Age: 24 Salary: 5000.55 Not an attribute
Smart Casting –
In Java or other programming languages, there is a requirement of explicit type casting on the variable before accessing the properties of that variable but Kotlin does a smart casting. The Kotlin compiler automatically converts the variable to a particular class reference once it’s passed through any conditional operator. Let’s take an example of Java, First of all, we check the type of the variable using the instanceOf operator and then cast it to the target type like this –
In Kotlin, smart type casting is one of the most interesting features available. We use is or !is operator to check the type of variable, and compiler automatically casts the variable to the target type like this-
length of String 13
Use of !is Operator Similarly using !is operator we can check the variable.
length of String 13
Note: Smart cast don’t work when the compiler can’t guarantee that the variable cannot change between the check and the usage. Smart casts are applicable according to the following rules:
- val local variables always works except for local delegated properties.
- val properties works only if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren’t applicable to open properties or properties that have custom getters.
- var local variables works only if the variable is not modified between the check and the usage, is not captured in a lambda that modifies it, and is not a local delegated property.
- var properties – never works because the variable can be modified at any time.