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-

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    var name = "Praveen"
    var age = 24
    var salary = 5000.55
    val employeeDetails: List<Any> = listOf(name,age,salary)
  
    for(attribute in employeeDetails) {
        if (attribute is String) {
            println("Name: $attribute")
        } else if (attribute is Int) {
            println("Age: $attribute")
        } else if (attribute is Double) {
            println("Salary: $attribute")
        } else {
            println("Not an attribute")
        }
    }
}

chevron_right


Output:



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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    var name = "Praveen"
    var age = 24
    var salary = 5000.55
    var emp_id = 12345f
    val employeeDetails: List<Any> = listOf(name, age, salary, emp_id)
  
    for (attribute in employeeDetails) {
        when (attribute) {
            is String -> println("Name: $attribute ")
            is Int -> println("Age: $attribute")
            is Double -> println("Salary: $attribute")
            else -> println("Not an attribute")
        }
    }
}

chevron_right


Output:

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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

Object ob = "GeeksforGeeks";
 
if(ob instanceof String) {
    // Explicit type casting
    String str = (String) ob;
 
    System.out.println("length of String " + str.length());
 }

chevron_right


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-

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    val str1: String? = "GeeksforGeeks"
    var str2: String? = null   // prints String is null
    if(str1 is String) {
         
        // No Explicit type Casting needed.
        println("length of String ${str1.length}")
    }
    else {
        println("String is null")
    }
}

chevron_right


Output:

length of String 13

Use of !is Operator
Similarly using !is operator we can check the variable.

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    val str1: String? = "GeeksforGeeks"
    var str2: String? = null  // prints String is null
    if(str1 !is String) {
        println("String is null")
    }
    else {
        println("length of String ${str1.length}")
    }
}

chevron_right


Output:

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.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.