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?
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.
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 .
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With