Skip to content

update parameterlists #1652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 5, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions _tour/multiple-parameter-lists.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,36 @@ println(res) // 55

Suggested use cases for multiple parameter lists include:

#### Single functional parameter
#### Drive type inference

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

```tut
def foldleft1[A, B](as: List[A], b0: B, op: (B, A) => B) = ???
```
numbers.foldLeft(0, (m: Int, n: Int) => m + n)

Then you'd like to call it in the following way, but will find that it doesn't compile:

```tut:fail
def notpossible = foldleft1(numbers, 0, _ + _)
```

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:
you will have to call it like one of the below ways:

```tut
def firstWay = foldleft1[Int, Int](numbers, 0, _ + _)
def secondWay = foldleft1(numbers, 0, (a: Int, b: Int) => a + b)
```
numbers.foldLeft(0)(_ + _)

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`

```tut
def foldleft2[A, B](as: List[A], b0: B)(op: (B, A) => B) = ???
def possible = foldleft2(numbers, 0)(_ + _)
```

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.
This definition doesn't need any type hints, and can infer all of its parameters.


#### Implicit parameters

Expand Down