Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
codecool Avatar asked Aug 04 '11 10:08

codecool


People also ask

What kind of parameters are not needed while calling a method in Scala?

A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle.

What are the method parameters in in Scala?

Methods in Scala can be parameterized by type as well as value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses. The method listOfDuplicates takes a type parameter A and value parameters x and length .

What is arity in Scala?

Arity. Represents the number of parameters passed into a function. More specific representations: A nullary function has an arity of zero. A unary function has an arity of one.

Which symbol is the method invocation operator?

Use the double-dot operator to invoke a method called AREA. Assume the existence of a table called RINGS, with a column CIRCLE_COL of structured type CIRCLE. Also, assume that the method AREA has been defined previously for the CIRCLE type as AREA() RETURNS DOUBLE .


2 Answers

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.

like image 82
Jean-Philippe Pellet Avatar answered Oct 03 '22 15:10

Jean-Philippe Pellet


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.

like image 10
Daniel C. Sobral Avatar answered Oct 03 '22 15:10

Daniel C. Sobral