Scala methods with no arguments

codecool picture codecool · Aug 4, 2011 · Viewed 11.5k times · Source

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?

Answer

Jean-Philippe Pellet picture Jean-Philippe Pellet · Aug 4, 2011

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.