没有参数的 Scala 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6939908/
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
Scala methods with no arguments
提问by codecool
In Scala there are two ways to define a method which takes no argument
在 Scala 中,有两种方法可以定义不带参数的方法
1 def a=println("hello")
2 def a()=println("hello")
These two methods are exactly same but (2) can be called with and without parentheses.
这两种方法完全相同,但是 (2) 可以带括号和不带括号调用。
Is there any special reason for which this feature is allowed in Scala.It confuses me which to use and when?
在 Scala 中允许使用此功能是否有任何特殊原因。它让我感到困惑,该使用哪个以及何时使用?
回答by Jean-Philippe Pellet
The general rule is that you should add an empty parameter list at both declaration site and call site whenever the method (not function) has side effects.
一般规则是,只要方法(不是函数)有副作用,就应该在声明站点和调用站点添加一个空参数列表。
Otherwise, Scala has the uniform access principle, so that clients don't need to know whether they're accessing a field or calling a side-effect-free method.
否则,Scala 具有统一访问原则,因此客户端不需要知道他们是在访问字段还是调用无副作用的方法。
回答by Daniel C. Sobral
The syntax without parenthesis is allowed so one can write this:
允许使用不带括号的语法,因此可以这样写:
abstract class X {
def f: Int
}
class Y extends X {
val f = 0
}
A code calling fon an Xdoes not need to know if it is a valor a def.
调用fan的代码X不需要知道它是 aval还是 a def。
The reason why one can omit parenthesis when calling methods with an empty list is to allow calling Java methods that would ideally not have parenthesis (but, because they are Java, they all have parenthesis).
在调用带有空列表的方法时可以省略括号的原因是允许调用理想情况下没有括号的 Java 方法(但是,因为它们是 Java,所以它们都有括号)。
As other said, there's a convention of using an empty parameter list when the method has side effects, and leaving them off otherwise.
正如其他人所说,当方法有副作用时,有一个使用空参数列表的约定,否则就不要使用它们。
回答by Ben James
It's a matter of style whether you choose to use parentheses to indicate a side-effecting method call.
是否选择使用括号来指示有副作用的方法调用是一种风格问题。
By the way, if you declare a purely side-effecting method using =, you should probably explicitly declare a Unitreturn type, like this:
顺便说一句,如果您使用 声明一个纯粹的副作用方法=,您可能应该显式声明一个Unit返回类型,如下所示:
def a: Unit = println("hello")
Note that any type can be coerced to Unit.
请注意,任何类型都可以强制转换为Unit.
If you do not want to explicitly declare a return type, you should probably omit the =. Then the compiler will infer a return type of Unit, even if the last expression returns something different:
如果不想显式声明返回类型,则可能应该省略=. 然后编译器将推断返回类型Unit,即使最后一个表达式返回不同的东西:
def a() { println("hello") }
Both of the above styles make refactoring safer, because modifying the method body will never cause the compiler to infer a different return type. IMO this explicitness of declaration is more important than call-site code style.
上述两种风格都使重构更安全,因为修改方法体永远不会导致编译器推断出不同的返回类型。IMO 这种声明的明确性比调用站点代码样式更重要。

