为什么以及何时需要在方法名称后面添加 _?
我对何时需要在方法之后使用 _
将其用作函数的规则有点犹豫。例如,为什么下面的 Foo
和 Nil
的 ::
之间存在差异?
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>)
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>)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您省略部分应用函数表达式中的所有参数时,您需要在其后面添加
_
除非编译器需要你使用它的地方。当您调用
Foo
上的方法::
时,编译器需要类型Int =>; Int
为参数。因此,您可以安全地省略该位置square
后面的下划线。但是,
Nil
上的::
方法可以采用任何 类型的参数。因此,它不会假设您打算部分应用该函数,而是会抱怨,除非您通过添加_
使其绝对明确。所以这些就是规则...我无法真正告诉您为什么这些规则;也许其他对编译器、类型系统和语言设计有更好了解的人能够告诉你原因。但我认为,如果没有这些规则,许多地方都会存在意外含糊不清的危险。
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.When you call the method
::
onFoo
, the compiler expects a typeInt => Int
for the parameter. So you can safely omit the underscore aftersquare
in that position.However, the
::
method onNil
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.