Smart Casts in Kotlin - Type Checks and Casts


Smart casts in Kotlin are a feature that allows the compiler to automatically cast an object after a type check, eliminating the need for explicit casting in most cases. In this guide, we'll explore smart casts, how they work, and their practical use cases.


Type Checks and Casts

In Kotlin, you can use the is operator for type checks and the as operator for explicit casts. For example:

val obj: Any = "Hello, Kotlin"
if (obj is String) {
// No explicit cast needed
val length = obj.length
}

In this example, the is operator checks if obj is of type String, and if true, you can directly access its properties and functions without explicit casting.


Type Checks and Casting

When you use the is operator, the compiler automatically performs a cast, known as a smart cast:

val obj: Any = "Hello, Kotlin"
if (obj is String) {
// Smart cast: obj is automatically cast to String
val length = obj.length
}

The smart cast allows you to work with the object as if it's of the specified type.


Using Smart Casts with When Expressions

Smart casts are commonly used in when expressions to handle different cases:

fun printLength(obj: Any) {
when (obj) {
is String -> println("String length: ${obj.length}")
is List<*> -> println("List size: ${obj.size}")
else -> println("Unknown type")
}
}
val string = "Hello"
val list = listOf(1, 2, 3)
printLength(string)
printLength(list)

Conclusion

Smart casts in Kotlin streamline the process of type checks and casting by automatically casting objects when a type check is successful. This feature improves code readability and safety, as it eliminates the need for explicit casting and reduces the risk of runtime errors.


Smart casts are particularly useful in scenarios where you need to work with objects of different types, such as when processing user input, handling polymorphism, or working with heterogeneous data structures.


Happy coding!