为什么以及何时需要在方法名称后加上_? [英] Why and when do I need to follow a method name with _?
问题描述
对于何时需要将_
用作函数的方法,我对规则有些不确定.例如,为什么下面的Foo
和Nil
的::
之间有区别?
I'm a bit shaky on the rules as to when you need a _
after a method to use it as a function. For example, why is there a difference between Foo
's and Nil
's ::
in the following?
def square(n: Int) = n * n
object Foo { def ::(f: Int => Int) = f(42) }
// ...
scala> Foo.::(square)
res2: Int = 1764
scala> Nil.::(square)
<console>:6: error: missing arguments for method square in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
Nil.::(square)
^
scala> Nil.::(square _)
res3: List[(Int) => Int] = List(<function1>)
推荐答案
在部分应用的函数表达式中省略所有参数时,除非编译器 ,否则您需要在其后跟随_
em>需要在您使用该功能的地方.
When you omit all parameters in a partially applied function expression, then you need to follow it with _
unless the compiler requires a function type in the place where you use it.
当您在Foo
上调用方法::
时,编译器期望该参数的类型为Int => Int
.因此,您可以安全地在该位置的square
之后省略下划线.
When you call the method ::
on Foo
, the compiler expects a type Int => Int
for the parameter. So you can safely omit the underscore after square
in that position.
但是,Nil
上的::
方法可以采用 any 类型的参数.因此,除非您通过添加_
使其绝对明确,否则它会抱怨,而不是假设您打算部分应用该功能.
However, the ::
method on Nil
can take a parameter of any type. So rather than assume that you meant to partially apply the function, it complains unless you make it absolutely explicit by adding _
.
这些就是规则...我真的不能启发您为什么这些规则;也许其他对编译器,类型系统和语言设计有更好了解的人可以告诉您原因.但是我认为,如果没有这些规则,许多地方就会有造成意外歧义的危险.
So those are the rules... I can't really enlighten you about why those are the rules; maybe somebody else who has better knowledge of the compiler, the type system, and the language design will be able to tell you why. But I assume that without these rules, there would be a danger of accidental ambiguity in many places.
这篇关于为什么以及何时需要在方法名称后加上_?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!