Smart Casting in Kotlin

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:

and a method defined in the main class to run the following example:

Result when you run the following example code:

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:

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *