Scala methods with no arguments

2019-01-17 21:47发布

问题:

In Scala there are two ways to define a method which takes no argument

    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.

Is there any special reason for which this feature is allowed in Scala.It confuses me which to use and when?

回答1:

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.



回答2:

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 f on an X does not need to know if it is a val or 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).

As other said, there's a convention of using an empty parameter list when the method has side effects, and leaving them off otherwise.



回答3:

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 Unit return type, like this:

def a: Unit = println("hello")

Note that any type can be coerced to 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:

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.