Why does this wildcarded function tells me it has the wrong number of parameters?

半腔热情 提交于 2019-12-30 11:33:06

问题


The offending code was:

<console>:47: error: wrong number of parameters; expected = 2
            terms.foldLeft(r.unitA)(r.add(_, _.eval(x)))

I solved my problem by writing:

 terms.foldLeft(r.unitA)((a,b) => r.add(a, b.eval(x)))

But I'd still like to know what prevented my initial attempt?


回答1:


From what I've read on this type of issue, when you use "_" as a place holder for an anonymous parameter of a function, the scope of that function is the innermost parenthesis containing it. So when you wrapped your two placeholders with r.add(), the scope of the params is lost. Check out this link and see if it helps explain the rules better.

http://www.scala-lang.org/node/2916




回答2:


Here is the section of the SLS 6.23:

http://iainmcgin.github.io/scala-ref-markdown/#placeholder-syntax-for-anonymous-functions

Updated link:

http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#placeholder-syntax-for-anonymous-functions

Daniel Sobral's post says:

"When you use "_" as a place holder for an anonymous parameter of a function, the scope of that function is the innermost parenthesis containing it. Most of the time.

Updated spin: I think the syntax explanation from the spec is easier to get, that the placeholder doesn't escape an enclosing Expr. There are various duplicate questions.



来源:https://stackoverflow.com/questions/16498543/why-does-this-wildcarded-function-tells-me-it-has-the-wrong-number-of-parameters

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