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?
views:
138answers:
3
+8
A:
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.
Dave Griffith
2010-10-07 01:13:42
What would you do, then, for a factory method? Would you write `def createAccount: Account` or `def createAccount(): Account`?
David
2010-10-07 01:53:19
For fully idiomatic Scala, factory methods are usually written on the companion object, and are named "apply". Then, you can create objects with the special syntax for apply: Account(args).
Dave Griffith
2010-10-07 03:09:38
The compiler accepts overriding definitions regardless of empty parameter lists: http://pastie.org/1204728 . Look for the string "empty parameter list" in the Language Specification.
mkneissl
2010-10-07 06:29:54
mkneissel is correct - you can override both ways between `method()` and `method`. You can only override a `val` with another `val`, however, and `method()()` is considered different (for the purposes of overriding, but not for name collisions) from `method()` and `method`.
Rex Kerr
2010-10-07 18:07:40
Thanks for the correction. Editing to fix.
Dave Griffith
2010-10-07 18:23:13
+1
A:
Scala Style Guide says to omit parentheses only when the method being called has no side-effects: http://davetron5000.github.com/scala-style/method_invocation/arity0/index.html
Alain O'Dea
2010-10-07 20:50:27
+1
A:
Other answers are great, but I also think it's worth mentioning that no-param methods allow for nice access to a classes fields, like so:
person.name
Because of parameterless methods, you could easily write a method to intercept reads (or writes) to the 'name' field without breaking calling code, like so
def name = { log("Accessing name!"); _name }
This is called the Uniform Access Principal
Adam Rabung
2010-10-16 01:03:42
my example was for getting, here's settingdef name_=(name : String) = { _name = name }
Adam Rabung
2010-10-16 12:08:03