Smart casts en Kotlin
Pasar una prueba is estrecha el tipo por el resto de la rama.
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)
}
Cómo funciona
- Tras
if (reading is Double),readinges Double — sin cast que escribir. - Las ramas
is Inteis Stringdelwhenestrechan igual. as?devuelve null en un cast fallido dondeaslanzaría.
Palabras clave y builtins usados aquí
AnyDoubleIntStringaselsefunifisreturnvalwhen
El intento, en números
- Líneas
- 18
- Caracteres a escribir
- 477
- Tokens
- 118
- Ritmo de tres estrellas
- 65 tpm
Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 109 segundos.
Paso 2 de 3 en Seguridad ante null; paso 17 de 27 en Fundamentos del lenguaje.