liveBook · Manning

Underscore notation

As explained in Functional Programming in Scala, Second Edition

Underscore notation is Scala syntax that represents anonymous-function parameters with underscores whose occurrences are introduced in left-to-right order.

Underscore notation abbreviates anonymous functions when Scala can infer their parameter types. Each underscore introduces and references a new unnamed parameter in left-to-right order. section 3.3.2

Replacing named parameters

The function (x, y) => x + y can become _ + _. Other examples include _ * 2, _.head, and _ drop _. In foldRight, productViaFoldRight(ns) uses _ * _ as its combining function. section 3.3.2

Use the shorthand when parameters occur simply and once. Prefer ordinarily named parameters when nested expressions such as foo(_, g(List(_ + 1), _)) make scope or correspondence difficult to read. section 3.3.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines parameter introduction order, gives examples, and advises named parameters when scoping becomes unclear.
Examples
Shows _ + _, _ * 2, _.head, _ drop _, and productViaFoldRight(ns) with _ * _.
What it assumes
Assumes anonymous functions and function-parameter positions while relying on Scala's ability to infer parameter types.
What you can do after
Apply it via Scala syntax to write concise anonymous functions and recognize when named parameters improve clarity.
How it connects
Connects anonymous functions, higher-order functions, foldRight, function parameters, and type inference.

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.