Funciones de extensión en Kotlin
Agrega funciones con aspecto de miembro a tipos que no son tuyos.
// An extension adds a member-looking function to a type you don't own.
fun String.shout() = uppercase() + "!"
fun Int.toElevationNote(): String =
if (this > 2400) "$this m: thin air" else "$this m: easy breathing"
fun main() {
println("summit day".shout())
println(2650.toElevationNote())
println(900.toElevationNote())
}
Cómo funciona
fun String.shout()vuelve legal"summit day".shout().- Dentro del cuerpo,
this(implícito o escrito) es el receptor. 2650.toElevationNote()se lee como si el Int siempre tuviera el método.
Palabras clave y builtins usados aquí
Stringelsefunifthis
El intento, en números
- Líneas
- 11
- Caracteres a escribir
- 324
- Tokens
- 79
- Ritmo de tres estrellas
- 70 tpm
Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 68 segundos.
Paso 3 de 3 en Funciones; paso 9 de 27 en Fundamentos del lenguaje.