With equals sign:
object HelloWorld { def main(args: Array[String]) = { println("Hello!") } }
Without equals sign:
object HelloWorld { def main(args: Array[String]) { println("Hello!") } }
Both of the above programs execute the same way. In the blog post Things I do not like in Scala I read that when the equals sign are missing, the method will return Unit
(same as Java's void
), so methods that return a value must use the equals sign. But methods that don't return a value can be written either way.
What is the best practice for using the equals sign in Scala methods that don't return a value?
=> 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 .
We can define a method's list of parameters in parentheses after its name. After the parameters list, we can provide a return type for the method with the leading colon sign. We then define a method's body after the equals sign. The compiler allows us to skip the curly braces if there is only one statement of code.
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.
A method belongs to an object (usually the class , trait or object in which you define it), whereas a function is by itself a value, and because in Scala every value is an object, therefore, a function is an object. The second def is an object of type Int => Int (the syntactic sugar for Function1[Int, Int] ).
I actually disagree pretty strongly with Daniel. I think the non-equal syntax should never be used. If your method is being exposed as an API and you're worried about accidentally returning the wrong type, add an explicit type annotation:
object HelloWorld { def main(args: Array[String]): Unit = { println("Hello!") 123 } }
The non-equal syntax is shorter and might look "cleaner", but I think it just adds the possibility of confusion. I have sometimes forgotten to add an equal sign and believed my method was returning a value when actually it was returning Unit. Because the non-equal and equal-with-inferred-type syntaxes are so visually similar, it's easy to miss this problem.
Even though it costs me a little more work, I prefer the explicit type annotations when they matter (namely, exposed interfaces).
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