Positional Notation for Parameters

Scala provides the notation _, the underscore, to represent parameters of a function value. While at first the underscore may appear cryptic, once you get used to it, you’ll see that it makes the code concise and easy to work with. You can use this symbol to represent a parameter, but only if you plan to refer to the parameter just once in the function value. You can use the underscore multiple times in a function value, but each use represents a subsequent parameter. Let’s look at an example to learn about this feature. In the following code we have a function value with two parameters:

FunctionValuesAndClosures/Underscore.scala
 
val​ arr = ​Array​(1, 2, 3, 4, 5)
 
 
val​ total = (0 /: arr) { (sum, elem) => ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.