Smart Casting is a feature of the Kotlin compiler that can rely on the previous conditions and circumstances of a variable to automatically cast that variable to the most appropriate, correct data type for that variable.
For example, I have a Student class:
1 2 3 4 5 |
package com.huongdankotlin class Student { val name: String = "" } |
and a method defined in the main class to run the following example:
1 2 3 4 5 |
fun casting(x: Any) { if (x is Student) { println(x.name) } } |
Result when you run the following example code:
1 2 3 4 5 6 |
fun main() { var student = Student() student.name = "Khanh" casting(student); } |
will be:
As you can see, the Kotlin compiler automatically casts the variable x in the casting() method to the Student object after checking it is an instance of the Student class and printing the student’s name.
If you check the variable x: if it is not an object of the Student class first, then return, otherwise, print the student’s name as follows:
1 2 3 4 5 6 7 |
fun casting(x: Any) { if (x !is Student) { return } println(x.name) } |
The Kotlin compiler also automatically casts the variable x to the instance of the Student class without any error:
The following code is also valid with Kotlin:
1 2 3 4 5 |
fun casting(x: Any) { if (x is Student && x.name.length >= 5) { println("Valid student name!") } } |
Since in the if statement, the first condition is satisfied, Kotlin will automatically cast x through the Student object and so we can call the name property of the Student object and check the length.
Your results are as follows:
In short, naturally, based on the previous context of the code, Kotlin will automatically cast the data types of the variables to a suitable object at compile time.