Scala underscore explanation

戏子无情 提交于 2019-12-05 00:10:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!