Possible Duplicate:
Functions vs methods in Scala
What is the difference between def foo = {} and def foo() = {} in Scala?
In scala we can define
def foo():Unit = println ("hello")
or
def foo:Unit = println ("hello")
I know they are not the same but what is the difference, and which should be used when?
If this has been answered before please point me to that link.
A Scala 2.x method of 0-arity can be defined with or without parentheses
(). This is used to signal the user that the method has some kind of side-effect (like printing out to std out or destroying data), as opposed to the one without, which can later be implemented asval.See Programming in Scala:
Terminology
There are some confusing terminology around 0-arity methods, so I’ll create a table here:
def foo: Intdef foo(): IntIt might sound cool to say "nullary method", but often people say it wrong and the readers will also be confused, so I suggest sticking with parameterless vs empty-paren methods, unless you’re on a pull request where people are already using the jargons.
() is no longer optional in Scala 2.13 or 3.0
In The great () insert, Martin Odersky made change to Scala 3 to require
()to call a method defined with(). This is documented in Scala 3 Migration Guide as:Note: Migration document gets the term wrong. It should read as:
Scala 2.13, followed Scala 3.x and deprecated the auto application of empty-paren methods in Eta-expand 0-arity method if expected type is Function0. A notable exception to this rule is Java-defined methods. We can continue to call Java methods such as
toStringwithout().