Skip to content

Commit 3226d12

Browse files
update parameterlists
1 parent ffe955e commit 3226d12

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

_tour/multiple-parameter-lists.md

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,21 +36,37 @@ println(res) // 55
3636

3737
Suggested use cases for multiple parameter lists include:
3838

39-
#### Single functional parameter
39+
#### Drive type inferrence
4040

41-
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:
41+
Say, you have the following method:
4242

43+
```tut
44+
def foldleft1[A, B](as: List[A], b0: B, op: (B, A) => B) = ???
4345
```
44-
numbers.foldLeft(0, (m: Int, n: Int) => m + n)
46+
47+
Then you'd like to call it in the following way, but will find that it doesn't compile:
48+
49+
```tut:fail
50+
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
51+
def notpossible = foldleft1(numbers, 0, _ + _)
4552
```
4653

47-
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, like this:
54+
you will have to call it like one of the below ways:
4855

56+
```tut
57+
def firstWay = foldleft1[Int, Int](numbers, 0, _ + _)
58+
def secondWay = foldleft1(numbers, 0, (a: Int, b: Int) => a + b)
4959
```
50-
numbers.foldLeft(0)(_ + _)
60+
61+
That's because scala won't be able to infer the type of the function `_ + _`, as it's still inferring `A` and `B`. By moving the paramter `op` to its own parameter list, `A` and `B` have been inferred, and `_ + _` will match the the inferred type `(Int, Int) => Int`
62+
63+
```tut
64+
def foldleft2[A, B](as: List[A], b0: B)(op: (B, A) => B) = ???
65+
def possible = foldleft2(numbers, 0)(_ + _)
5166
```
5267

53-
this would not be possible with only a single parameter list, as the Scala compiler would not be able to infer the parameter types of the function.
68+
This definition doesn't need any type hints, and can infer all of its parameters.
69+
5470

5571
#### Implicit parameters
5672

0 commit comments

Comments
 (0)