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?
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.
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".
def keyword: “def” keyword is used to declare a function in Scala. function_name: It should be valid name in lower camel case.
=> 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 .
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.
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