scala - 带括号和不带括号的函数的区别

标签 scala

Possible Duplicate:
Functions vs methods in Scala
What is the difference between def foo = {} and def foo() = {} in Scala?

在scala中我们可以定义

def foo():Unit = println ("hello")

def foo:Unit = println ("hello")

我知道它们不一样,但是有什么区别,什么时候应该使用哪个?

如果之前已回答过此问题,请指出该链接。

最佳答案

可以使用或不使用括号来定义 0 元数的 Scala 2.x 方法 () 。这用于向用户发出信号,表明该方法具有某种副作用(例如打印到标准输出或破坏数据),而不是没有副作用,稍后可以将其实现为 val .

参见Programming in Scala :

Such parameterless methods are quite common in Scala. By contrast, methods defined with empty parentheses, such as def height(): Int, are called empty-paren methods. The recommended convention is to use a parameterless method whenever there are no parameters and the method accesses mutable state only by reading fields of the containing object (in particular, it does not change mutable state).

This convention supports the uniform access principle [...]

To summarize, it is encouraged style in Scala to define methods that take no parameters and have no side effects as parameterless methods, i.e., leaving off the empty parentheses. On the other hand, you should never define a method that has side-effects without parentheses, because then invocations of that method would look like a field selection.

术语

围绕 0 元数方法有一些令人困惑的术语,因此我将在此处创建一个表格:

<表类=“s-表”> <标题> 用 Scala 编程 scala/scala 术语 <正文> def foo: Int 无参数方法 无效方法 def foo(): Int 空括号方法 二元法

说“空方法”可能听起来很酷,但人们常常说错了,读者也会感到困惑,所以我建议坚持使用无参数方法与空括号方法,除非你正在处理一个拉取请求,其中人们已经在使用这些行话了。

() 在 Scala 2.13 或 3.0 中不再是可选的

The great () insert ,Martin Odersky 对 Scala 3 进行了更改,要求 ()调用 () 定义的方法。这记录在Scala 3 Migration Guide中如:

Auto-application is the syntax of calling a nullary method without passing an empty argument list.

注意:迁移文档中的术语有误。它应该读作:

Auto-application is the syntax of calling a empty-paren (or "nilary") method without passing an empty argument list.

Scala 2.13 遵循 Scala 3.x 并在 Eta-expand 0-arity method if expected type is Function0 中弃用了空括号方法的自动应用。此规则的一个值得注意的异常(exception)是 Java 定义的方法。我们可以继续调用Java方法如toString没有() .

关于scala - 带括号和不带括号的函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7600910/

相关文章:

function - Scala 定义函数标准

algorithm - 树中的最大元素

scala - emacs scala 模式,无法使其自动激活

scala - 什么是 Scala 的简单构建工具 (sbt) 以及为什么使用它?

scala - 验证 sbt 安装时出错

scala - 尝试远程调试 Spark 应用程序 : java. io.IOException“握手失败 - 连接过早关闭”

scala - 上类型界限相对于子类型的优点

json - 带有桑格利亚汽酒的 GraphQL 模式

scala - 类型和泛型 : difference between `[X <: Int]` and `{type X <: Int }`

scala - 如何在 Spark/Scala 中使用窗口函数使用 countDistinct?