Scala methods with no arguments

坚强是说给别人听的谎言 提交于 2019-11-28 08:21:35

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!