O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) => ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required