2

Possible Duplicate:
Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments?

Consider we have a class Foo with a method bar (which does takes no arguments and return the string "bar"). There are two ways to implement bar

The first one is

class Foo {
  def bar() = "bar"
}

The second one is

class Foo {
  def bar = "bar"
}

While both do basically the same, they need to be called differently, the first one like this

someFoo.bar()

and the second one

someFoo.bar

Why should I use one over the other and what's the fundamental difference?

Community
  • 1
  • 1
helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 2
    I think it is one of the most frequent questions with scala tag I see on SO :) – 4e6 Oct 14 '12 at 17:54
  • *they need to be called differently* Actually, nothing stops you from calling method-defined-with-parentheses without braces: `def foo() {}; foo` (but not vise versa) – om-nom-nom Oct 14 '12 at 18:22

2 Answers2

1

Defining a method without arguments without parentheses implies that the method is pure (it has no side effects and doesn't depend on the state of program). Such methods cannot be called with parentheses:

class Square(val side: Int) {
  def area = side * side
}

s = new Square(10);
s.area //ok
s.area() //compilation error

Calling a method without arguments with parentheses implies that the method has some side effects and a return type of Unit. A method defined with empty parentheses can be called with or without them.

class Foo {
  def bar(): Unit = println("bar")
}

f = new Foo();
f.bar; //ok, bad style
f.bar(); // good
Bozhidar Batsov
  • 55,802
  • 13
  • 100
  • 117
1
  1. Neither of them needs to be called with parantheses. Yet def bar = "bar" is required to be called without parantheses, since the parantheses will be implied to be applied to it's result, thus in this case calling bar() will have the same effect as "bar"().

  2. It's only a matter of convention. In my practice I've seen two:

    • Standard (used in the standard library and most 3rd party ones). Drop the parantheses when the method produces no side effects. Being "pure", i.e. besides not causing any side effects also not depending on the state, however is not a requirement. According to this convention your second example would be the correct one.
    • Scalaz. Drop the parantheses whenever there are no arguments to a method, i.e. the method may produce side effects. For example they pimp a method print without parentheses.

Bozhidar presented another convention, but, honestly, it's the first time I've been exposed to it.

Nikita Volkov
  • 42,792
  • 11
  • 94
  • 169