Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments?

As far as I understand, in Scala we can define a function with no parameters either by using empty parentheses after its name, or no parentheses at all, and these two definitions are not synonyms. What is the purpose of distinguishing these 2 syntaxes and when should I better use one instead of another?

like image 755
Ivan Avatar asked Oct 07 '10 00:10

Ivan


People also ask

What does it means when there are empty parentheses after a function name?

The empty parentheses after the name indicate that this function doesn't take any arguments. Later we will build functions that take arguments as their inputs.

What do empty parentheses mean?

Empty parentheses mean that the function you are calling takes no arguments or it has default arguments pre-defined. When a function is part of a class, we call it "method".

How do you define a function in Scala?

def keyword: “def” keyword is used to declare a function in Scala. function_name: It should be valid name in lower camel case.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .


1 Answers

It's mostly a question of convention. Methods with empty parameter lists are, by convention, evaluated for their side-effects. Methods without parameters are assumed to be side-effect free. That's the convention.

like image 56
Dave Griffith Avatar answered Oct 08 '22 15:10

Dave Griffith