views:

138

answers:

3

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?

+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
What would you do, then, for a factory method? Would you write `def createAccount: Account` or `def createAccount(): Account`?
David
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
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
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
Thanks for the correction. Editing to fix.
Dave Griffith
+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
+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
This is meant to work for setting a property too??
Ivan
my example was for getting, here's settingdef name_=(name : String) = { _name = name }
Adam Rabung
Yes, I use this. But I wonder, does this mean "name_ =" or "name _="?
Ivan