🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Lambdas

A lambda is a small unnamed function that you can store or pass around like a value. It states its inputs, an arrow, and the expression that works out its result.

A lambda stored in a val

The lambda (x: Int) => x * 2 doubles its input, and it is stored in the val double. Calling double works just like calling a function.

@main def main(): Unit =
  val double = (x: Int) => x * 2
  println(double(4))
  println(double(9))

A lambda with two inputs

This lambda takes two Int inputs and adds them. The stored lambda is then called with two arguments, like a def with two parameters.

@main def main(): Unit =
  val add = (a: Int, b: Int) => a + b
  println(add(3, 4))
  println(add(10, 5))

Passing a lambda to a def

The def run takes a function parameter f of type (Int) => Int, plus a number. It applies f to the number, and the caller passes the lambda stored in triple.

def run(f: (Int) => Int, n: Int): Int = f(n)

@main def main(): Unit =
  val triple = (x: Int) => x * 3
  println(run(triple, 5))
  println(run(triple, 2))

Example

def transform(f: (Int) => Int, n: Int): Int = f(n)

@main def main(): Unit =
  val square = (x: Int) => x * x
  val plusTen = (x: Int) => x + 10
  println(square(6))
  println(transform(square, 4))
  println(transform(plusTen, 4))

Key points

  • Lambda: A lambda is a small function written without a name, in the form inputs, arrow, body.
  • Arrow: The arrow => separates the inputs on the left from the body on the right.
  • Stored in a val: A lambda can be stored in a val and later called by that name, like a function.
  • Two inputs: A lambda can take several inputs, written in parentheses and separated by commas.
  • Function parameter: A def can take a function as a parameter, so the caller chooses what the def runs.
  • Function type: The type (Int) => Int means a function that takes one Int and gives back one Int.

In this example, two lambdas are stored in vals, one that squares its input and one that adds ten. The first call runs square directly and prints 36. The transform def then takes each lambda as its function argument and applies it to 4, printing 16 and then 14.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

With val double = (x: Int) => x * 2, what does double(7) give back?