liveBook · Manning

Lambda

As explained in Functional Programming in Scala, Second Edition

A function expression without a declared name, typically written using parameter and body syntax.

A lambda is a function expression without a declared name. In Scala, parameters appear before => and the function body after it: (x: Int) => x == 9. Lambdas can be supplied directly where higher-order functions expect function values. section 2.4.2

Passing a lambda to findFirst

findFirst(Array(7, 9, 13), (x: Int) => x == 9) returns 1. The lambda tests each array element without requiring a separately named method. When Scala can infer the parameter type, the annotation may be omitted. section 2.4.2

Lambdas support several increasingly compact forms:

  • Write explicit parameters when clarity matters: (x: Int, y: Int) => x == y. section 2.4.2
  • Use inferred parameters when context supplies their types: (x, y) => x < y. section 2.4.2
  • Use underscore notation for short expressions such as _ + _, _ * 2, or _.head; avoid it when parameter scope becomes unclear. section 3.3.2

Because lambdas are values, they can be passed to and returned from functions. This enables reusable operations such as foldRight, curry, uncurry, and compose, while keeping the varying behavior explicit. section 2.7 section 3.3.2

Listing 3.2 Right folds and simple uses
def foldRight[A, B](as: List[A], acc: B, f: (A, B) => B): B =
  as match
    case Nil => acc
    case Cons(x, xs) => f(x, foldRight(xs, acc, f))
 
def sumViaFoldRight(ns: List[Int]) =
  foldRight(ns, 0, (x,y) => x + y)
 
def productViaFoldRight(ns: List[Double]) =
  foldRight(ns, 1.0, _ * _)                 #1

Compare named and anonymous functions in foldRight: the same traversal accepts (x, y) => x + y or the shorter _ * _ form. section 3.3.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines lambda syntax, type inference, underscore shorthand, and composition, while deferring precise underscore-scoping rules to the language specification.
Examples
Uses findFirst predicates, array-sorting comparisons, charge coalescing, foldRight arithmetic, and underscore expressions.
What you can do after
Apply it via higher-order functions, predicates, folds, currying, composition, and concise Scala collection operations.
How it connects
Connects lambdas to higher-order functions, function types, currying, composition, and folds over lists.

Also explained in

Compare how 18 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.