scala 方法调用后的下划线是什么意思? [英] What does an underscore after a scala method call mean?
问题描述
scala 文档 有一个代码示例,其中包括以下行:
The scala documentation has a code example that includes the following line:
val numberFunc = numbers.foldLeft(List[Int]())_
方法调用后的下划线是什么意思?
What does the underscore after the method call mean?
推荐答案
这是一个部分应用的函数.您只向 foldLeft
提供第一个参数(初始值),但不提供第二个;你把它推迟到以后.在您链接的文档中,他们在下一行定义 squares
:
It's a partially applied function. You only provide the first parameter to foldLeft
(the initial value), but you don't provide the second one; you postpone it for later. In the docs you linked they do it in the next line, where they define squares
:
val numberFunc = numbers.foldLeft(List[Int]())_
val squares = numberFunc((xs, x) => xs:+ x*x)
看到 (xs, x) =>xs:+ x*x
,这是您在定义 numberFunc
时遗漏的第二个参数.如果您立即提供了它,那么 numberFunc
将不是函数 - 它是计算值.
See that (xs, x) => xs:+ x*x
, that's the missing second parameter which you omitted while defining numberFunc
. If you had provided it right away, then numberFunc
would not be a function - it would be the computed value.
所以基本上整个事情也可以用咖喱的形式写成一行:
So basically the whole thing can also be written as a one-liner in the curried form:
val squares = numbers.foldLeft(List[Int]())((xs, x) => xs:+ x*x)
但是,如果你希望能够一次又一次地重用foldLeft,拥有相同的集合和初始值,但每次都提供不同的函数,那么定义一个单独的numbersFunc
(就像他们在文档中所做的那样)并用不同的功能重用它,例如:
However, if you want to be able to reuse foldLeft over and over again, having the same collection and initial value, but providing a different function every time, then it's very convinient to define a separate numbersFunc
(as they did in the docs) and reuse it with different functions, e.g.:
val squares = numberFunc((xs, x) => xs:+ x*x)
val cubes = numberFunc((xs, x) => xs:+ x*x*x)
...
请注意,编译器错误消息非常简单,以防您忘记下划线:
Note that the compiler error message is pretty straightforward in case you forget the underscore:
错误:trait 中方法 foldLeft 缺少参数列表LinearSeqOptimized 未应用的方法仅转换为函数当需要函数类型时.您可以进行此转换通过编写 foldLeft _
或 foldLeft(_)(_)
而不是显式foldLeft
.val numberFunc = numbers.foldLeft(ListInt)
Error: missing argument list for method foldLeft in trait LinearSeqOptimized Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing
foldLeft _
orfoldLeft(_)(_)
instead offoldLeft
. val numberFunc = numbers.foldLeft(ListInt)
哈哈,我刚刚意识到他们对文档中的 cubes
做了完全相同的事情.
Haha I just realized that they did the exact same thing with cubes
in the documentation.
这篇关于scala 方法调用后的下划线是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!