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

















