问题
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))
?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/37589210/scala-underscore-explanation