Open In App

Kotlin | Type Checking and Smart Casting

Last Updated : 28 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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- 

Kotlin




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")
        }
    }
}


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 – 

Kotlin




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")
        }
    }
}


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 – 

Java




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


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- 

Kotlin




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")
    }
}


Output:

length of String 13

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

Kotlin




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}")
    }
}


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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads