typestar

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

  1. Tras if (reading is Double), reading es Double — sin cast que escribir.
  2. Las ramas is Int e is String del when estrechan igual.
  3. as? devuelve null en un cast fallido donde as lanzaría.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 2 de 3 en Seguridad ante null; paso 17 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →