为什么以及何时需要在方法名称后面添加 _?

发布于 2024-08-17 19:44:28 字数 575 浏览 2 评论 0原文

我对何时需要在方法之后使用 _ 将其用作函数的规则有点犹豫。例如,为什么下面的 FooNil:: 之间存在差异?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟沫凡尘 2024-08-24 19:44:28

当您省略部分应用函数表达式中的所有参数时,您需要在其后面添加 _ 除非编译器需要你使用它的地方。

当您调用 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 :: on Foo, the compiler expects a type Int => Int for the parameter. So you can safely omit the underscore after square in that position.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文