A Scala 2.x 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
.
See 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.
Terminology
There are some confusing terminology around 0-arity methods, so I'll create a table here:
|
Programming in Scala |
scala/scala jargon |
def foo: Int |
parameterless methods |
nullary method |
def foo(): Int |
empty-paren methods |
nilary method |
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…