Lambdas y valores función en Scala
Literales de función, la abreviatura _ y un método que recibe una función como parámetro.
// A function literal is written params => body.
val twice = (n: Int) => n * 2
// Inside map the parameter type is already known, so drop it.
val wordLengths = List("ash", "willow", "oak").map(w => w.length)
// _ is shorthand for a parameter used exactly once.
val shouted = List("ash", "oak").map(_.toUpperCase)
// A method can take a function as a parameter and call it.
def applyTwice(start: Int, step: Int => Int): Int = step(step(start))
def lambdaDemo(): Unit =
println(twice(21))
println(wordLengths.max)
println(shouted.mkString(", "))
println(applyTwice(3, twice))
println(applyTwice(3, _ + 10))
Cómo funciona
val twice = (n: Int) => n * 2vincula un literal de función a un val..map(w => w.length)infiere el tipo del parámetro de la colección, y.map(_.toUpperCase)reduce a_un uso único.applyTwicerecibe la funciónstep: Int => Int; se llamaapplyTwice(3, twice)yapplyTwice(3, _ + 10).
Palabras clave y builtins usados aquí
defval
El intento, en números
- Líneas
- 18
- Caracteres a escribir
- 608
- Tokens
- 124
- Ritmo de tres estrellas
- 70 tpm
Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 106 segundos.
Paso 3 de 3 en Funciones; paso 9 de 27 en Fundamentos del lenguaje.