Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala underscore explanation

Have a look at these scala snippets: if we have something like this:

List(List(1, 2), List(3, 4), List(5)) map (x => (x.size))

we can shorten it to:

List(List(1, 2), List(3, 4), List(5)) map ((_.size))

but, if we have something like this:

List(List(1, 2), List(3, 4), List(5)) map (x => (x.size, x.size))

why can't we shorten it to:

List(List(1, 2), List(3, 4), List(5)) map ((_.size, _.size))

?

like image 744
GA1 Avatar asked Jun 02 '16 10:06

GA1


2 Answers

An amount of placeholders should be equals amount of function parameters. In your case map has 1 parameter that's why you can't use two placeholders.

like image 183
Sergii Lagutin Avatar answered Sep 22 '22 15:09

Sergii Lagutin


Because List(List(1, 2), List(3, 4), List(5)) map ((_.size, _.size)) has a different meaning, namely

List(List(1, 2), List(3, 4), List(5)) map ((x => x.size, y => y.size))

(you can see this from the error message). This obviously doesn't compile, because map doesn't accept a tuple of two functions.

like image 32
Alexey Romanov Avatar answered Sep 21 '22 15:09

Alexey Romanov