What is the difference between def foo = {} and def foo() = {} in Scala?

If you include the parentheses in the definition you can optionally omit them when you call the method. If you omit them in the definition you can’t use them when you call the method.

scala> def foo() {}
foo: ()Unit

scala> def bar {}
bar: Unit

scala> foo

scala> bar()
<console>:12: error: Unit does not take parameters
       bar()
          ^

Additionally, you can do something similar with your higher order functions:

scala> def baz(f: () => Unit) {}
baz: (f: () => Unit)Unit

scala> def bat(f: => Unit) {}
bat: (f: => Unit)Unit

scala> baz(foo)    

scala> baz(bar)
<console>:13: error: type mismatch;
 found   : Unit
 required: () => Unit
       baz(bar)
           ^
scala> bat(foo)

scala> bat(bar)  // both ok

Here baz will only take foo() and not bar. What use this is, I don’t know. But it does show that the types are distinct.

Leave a Comment