fun describe(x: Any): String {
if (x is String) {
// x is now smart-cast to String here — can call String methods directly
return "string of length ${x.length}"
}
if (x is List<*>) {
return "list of ${x.size} items"
}
return "something else"
}
fun greet(name: String?) {
if (name == null) return
// Below this line `name` is smart-cast to non-null String
println("Hello, ${name.uppercase()}")
}
// In when:
fun area(shape: Any): Double = when (shape) {
is Pair<*, *> -> {
// Smart cast only works if the type info is preserved (here we'd
// need explicit casts since generics are erased at runtime).
0.0
}
is List<*> -> shape.size.toDouble() // smart cast → List<*>
else -> 0.0
}
Create a free account and build your private vault. Share publicly whenever you want.