-
Notifications
You must be signed in to change notification settings - Fork 22
Kotlin: Smart Casts
Devrath edited this page Dec 26, 2023
·
2 revisions
- Smart casting refers to the automatic casting of a variable to a certain type when a condition is met
- This helps to streamline the code and improve the type of safety
- It helps to avoid specific types of safety checks
- The most common scenario for smart casting in Kotlin is with is checks.
- When you use the is operator to check if a variable is of a certain type, and the check passes, Kotlin automatically casts the variable to that type within the scope where the check is true.
code
fun printStringLength(value: Any) {
if (value is String) {
// Inside this block, 'value' is automatically cast to String
println("Length of the string is ${value.length}")
} else {
println("Not a string")
}
}
In the when expression, each branch with an is check results in smart casting of value to the corresponding type within that branch.
fun processValue(value: Any) {
when (value) {
is String -> println("Processing string: ${value.length}")
is Int -> println("Processing integer: $value")
else -> println("Unknown type")
}
}