Smart Cast in Kotlin: What It Is and How It Works
smart cast is a feature where the compiler automatically casts a variable to a more specific type after checking its type with conditions like is. This lets you use the variable without manually casting it, making code safer and easier to read.How It Works
Smart cast works like a helpful assistant that remembers the type of a variable after you check it. Imagine you have a box that might contain different things. If you look inside and see it contains a book, you can safely treat it as a book without asking again.
In Kotlin, when you check a variable's type using is or check for null, the compiler remembers this information and automatically treats the variable as that type in the following code. This avoids the need for extra manual casts and reduces errors.
Example
This example shows how Kotlin smart casts a variable after a type check, so you don't need to cast it manually.
fun printLength(obj: Any) {
if (obj is String) {
// obj is automatically cast to String here
println("Length of string: ${obj.length}")
} else {
println("Not a string")
}
}
fun main() {
printLength("Hello")
printLength(123)
}When to Use
Use smart casts whenever you need to work with variables that can hold different types or might be null. It helps you write cleaner code by avoiding manual casts and makes your code safer by ensuring the type is checked before use.
For example, when handling user input that could be a string or a number, or when working with nullable types, smart casts let you safely access properties or methods without extra code.
Key Points
- Smart cast automatically converts a variable to a specific type after a type check.
- It works with
ischecks and null checks. - It reduces the need for manual casting and makes code safer.
- Smart cast only works when the compiler can guarantee the variable's type won't change.