开发者

Scala methods with no arguments

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜