You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: _tour/multiple-parameter-lists.md
+27-5Lines changed: 27 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -25,20 +25,42 @@ def foldLeft[B](z: B)(op: (B, A) => B): B
25
25
26
26
```tut
27
27
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
28
-
val res = numbers.foldLeft(0)((m: Int, n: Int) => m + n)
28
+
val res = numbers.foldLeft(0)((m, n) => m + n)
29
29
print(res) // 55
30
30
```
31
31
32
-
Starting with an initial value of 0, `foldLeft` applies the function `(m: Int, n: Int) => m + n` to each element in the List and the previous accumulated value.
32
+
Starting with an initial value of 0, `foldLeft` applies the function `(m, n) => m + n` to each element in the List and the previous accumulated value.
33
33
34
34
Multiple parameter lists have a more verbose invocation syntax; and hence should be used sparingly. Suggested use cases include:
35
35
36
-
1.##### Implicit parameters
36
+
1.##### Single functional parameter
37
+
In case of a single functional parameter, like `op` in the case of `foldLeft` above, multiple parameter lists allow a concise syntax to pass an anonymous function to the method. Without multiple parameter lists, the code would look like this:
38
+
```
39
+
numbers.foldLeft(0, {(m: Int, n: Int) => m + n})
40
+
```
41
+
Note that the use of multiple parameter lists here also allows us to take advantage of Scala type inference to make the code more concise as shown below; which would not be possible for a non-curried definition.
42
+
43
+
```
44
+
numbers.foldLeft(0)(_ + _)
45
+
```
46
+
47
+
Also, it allows us to fix the parameter `z` and pass around a partial function and reuse it as shown below:
In case of a single functional parameter, like `op` in the case of `foldLeft` above, multiple parameter lists allow a concise syntax to pass an anonymous function to the method.
0 commit comments