scala 带括号和不带括号的函数的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7600910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between function with parentheses and without
提问by Jus12
Possible Duplicate:
Functions vs methods in Scala
What is the difference between def foo = {} and def foo() = {} in Scala?
可能的重复:
Scala 中的函数与方法 在 Scala 中
def foo = {} 和 def foo() = {} 之间有什么区别?
In scala we can define
在 Scala 中,我们可以定义
def foo():Unit = println ("hello")
or
或者
def foo:Unit = println ("hello")
I know they are not the same but what is the difference, and which should be used when?
我知道它们不一样,但有什么区别,应该在什么时候使用?
If this has been answered before please point me to that link.
如果之前已经回答过这个问题,请把我指向那个链接。
回答by Eugene Yokota
A Scala method of 0-arity can be defined with or without parentheses (). This is used to signal the user that the method has some kind of side-effect (like printing out to std out or destroying data), as opposed to the one without, which can later be implemented as val.
可以使用或不使用括号来定义 0 元数的 Scala 方法()。这用于向用户表明该方法具有某种副作用(例如打印到标准输出或破坏数据),而不是没有的,稍后可以将其实现为val.
See Programming in Scala:
参见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.
这种无参数方法在 Scala 中很常见。相比之下,使用空括号定义的方法,例如 def height(): Int,称为空括号方法。推荐的约定是在没有参数时使用无参数方法,并且该方法仅通过读取包含对象的字段来访问可变状态(特别是,它不会更改可变状态)。
该公约支持统一访问原则 [...]
总而言之,Scala 鼓励将不带参数且没有副作用的方法定义为无参数方法,即去掉空括号。另一方面,你不应该定义一个没有括号的有副作用的方法,因为那样调用那个方法看起来就像一个字段选择。

