typestar

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

  1. val twice = (n: Int) => n * 2 binds a function literal to a val.
  2. .map(w => w.length) infers the parameter type from the collection, and .map(_.toUpperCase) shortens a single use to _.
  3. def applyTwice(start: Int, step: Int => Int): Int takes a function parameter, called as applyTwice(3, twice) and applyTwice(3, _ + 10).

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Functions, step 9 of 27 in Language basics.

← Previous Next →