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