Smart casts in Kotlin
Passing an is-check narrows the type for the rest of the branch.
fun label(reading: Any): String {
// A passed is-check narrows the type for the rest of the branch.
if (reading is Double) return "temp ${reading * 1.8 + 32} F"
return when (reading) {
is Int -> "wind $reading km/h"
is String -> "note: ${reading.trim()}"
else -> "unreadable"
}
}
fun main() {
println(label(-3.5))
println(label(38))
println(label(" bridge icy "))
// as? yields null instead of throwing on a bad cast.
val maybe: Int? = ("17" as Any) as? Int
println(maybe)
}
How it works
- After
if (reading is Double),readingis a Double — no cast to write. whenbranches onis Intandis Stringnarrow the same way.as?returns null on a failed cast whereaswould throw.
Keywords and builtins used here
AnyDoubleIntStringaselsefunifislabelmainreturnvalwhen
The run, in numbers
- Lines
- 18
- Characters to type
- 477
- Tokens
- 118
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 109 seconds.
Step 2 of 3 in Null safety, step 17 of 27 in Language basics.