Lambdas & function values in Scala
Function literals, the _ shorthand, and a method that takes a function as a parameter.
// 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))
How it works
val twice = (n: Int) => n * 2binds a function literal to a val..map(w => w.length)infers the parameter type from the collection, and.map(_.toUpperCase)shortens a single use to_.def applyTwice(start: Int, step: Int => Int): Inttakes a function parameter, called asapplyTwice(3, twice)andapplyTwice(3, _ + 10).
Keywords and builtins used here
IntListUnitapplyTwicedeflambdaDemoval
The run, in numbers
- Lines
- 18
- Characters to type
- 608
- Tokens
- 124
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 106 seconds.
Step 3 of 3 in Functions, step 9 of 27 in Language basics.