Start Coding

Topics

Kotlin Smart Casts

Kotlin smart casts are a powerful feature that simplifies type checking and casting. They automatically cast types in certain conditions, making your code more concise and safer.

How Smart Casts Work

When you use a type-checking condition (like is or !is), Kotlin's compiler tracks this information. It then automatically casts the variable to the appropriate type within the scope where the condition is true.

Basic Usage

Here's a simple example demonstrating smart casts:


fun printLength(obj: Any) {
    if (obj is String) {
        // obj is automatically cast to String in this scope
        println(obj.length)
    }
}
    

In this example, once we've checked that obj is a String, we can directly use obj.length without explicit casting.

Smart Casts with When Expression

Smart casts work particularly well with Kotlin's When Expression:


fun describe(obj: Any): String =
    when (obj) {
        is Int -> "It's an integer: $obj"
        is String -> "It's a string of length ${obj.length}"
        is List<*> -> "It's a list with ${obj.size} items"
        else -> "Unknown type"
    }
    

Limitations and Considerations

  • Smart casts only work with immutable values (val) or local variables.
  • They don't work with mutable properties that could have been changed by other threads.
  • Smart casts are not applicable to generic types with type parameters.

Null Safety and Smart Casts

Smart casts also work with Nullable Types. When you check for null, Kotlin automatically casts to the non-null type:


fun printUppercase(str: String?) {
    if (str != null) {
        // str is automatically cast to non-null String here
        println(str.toUpperCase())
    }
}
    

Conclusion

Kotlin smart casts are a powerful feature that enhances code readability and safety. They work seamlessly with Kotlin's type system, null safety features, and control flow statements. By leveraging smart casts, you can write more concise and expressive code, reducing the need for explicit type checks and casts.