Kotlin
Beginner
1 min read
Safe Casts and Smart Casts
Example
open class Animal(val name: String)
class Dog(name: String) : Animal(name) { fun bark() = println("$name: Woof!") }
class Cat(name: String) : Animal(name) { fun purr() = println("$name: Purrr...") }
fun interact(animal: Animal) {
// Smart cast after is check
when (animal) {
is Dog -> animal.bark() // animal is Dog here
is Cat -> animal.purr() // animal is Cat here
else -> println("${animal.name} just stares at you")
}
}
fun parseNumber(value: Any): Double? {
// Safe cast — returns null on failure
val str = value as? String ?: return (value as? Number)?.toDouble()
return str.toDoubleOrNull()
}
fun nullSmartCast(text: String?) {
// Early return eliminates nullable in the rest of the function
if (text == null) return
println(text.uppercase()) // text is String here, not String?
}
fun main() {
val animals: List<Animal> = listOf(Dog("Rex"), Cat("Whiskers"), Animal("Bird"))
animals.forEach(::interact)
println(parseNumber("3.14")) // 3.14
println(parseNumber(42)) // 42.0
println(parseNumber(true)) // null
nullSmartCast("hello") // HELLO
nullSmartCast(null) // (nothing printed)
}