Open In App

Kotlin Type Checking and Smart Casting

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Kotlin allows you to determine the type of a variable at runtime using the is operator. This feature is commonly used to handle logic based on the dynamic type of an object, enabling type-safe operations within control flow blocks.

Using if-else Blocks for Type Checking

Kotlin
fun main() {
    val name = "Praveen"
    val age = 24
    val 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("Unknown attribute")
        }
    }
}

Output:

Name: Praveen
Age: 24
Salary: 5000.55

Explanation of the above Program:

Here, we define variables of different types and store them in a list. As we iterate over each element, we use the is operator to check its type and print a relevant message.

Replacing if-else with when Expression

The same logic can be implemented more elegantly using Kotlin’s when expression, which serves as a more concise and readable alternative to multiple if-else checks.

Kotlin
fun main() {
    val name = "Praveen"
    val age = 24
    val salary = 5000.55
    val empId = 12345f
    val employeeDetails: List<Any> = listOf(name, age, salary, empId)

    for (attribute in employeeDetails) {
        when (attribute) {
            is String -> println("Name: $attribute")
            is Int -> println("Age: $attribute")
            is Double -> println("Salary: $attribute")
            else -> println("Unknown attribute")
        }
    }
}

Output:

Name: Praveen
Age: 24
Salary: 5000.55
Unknown 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.

Comparison with Java:

Java
Object ob = "GeeksforGeeks";

if(ob instanceof String) {
    String str = (String) ob;  // Explicit cast required
    System.out.println("Length: " + 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.

Kotlin Equivalent with Smart Casting:

Kotlin
fun main() {
    val str1: String? = "GeeksforGeeks"
    val str2: String? = null

    if (str1 is String) {
        // Smart cast: No need for explicit casting
        println("Length of string: ${str1.length}")
    } else {
        println("String is null")
    }
}

Output:

Length of string: 13

Using !is Operator

The !is operator checks if the variable is not of the specified type.

Kotlin
fun main() {
    val str1: String? = "GeeksforGeeks"

    if (str1 !is String) {
        println("String is null")
    } else {
        println("Length of string: ${str1.length}")
    }
}

Output:

Length of string: 13

Smart Cast Limitations

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.

Next Article
Article Tags :

Similar Reads