3

If we have a method:

def hello() = "world"

I'm told that we can call it as:

hello()

also

hello

They both work and will output world, but why?


PS:

I see some words in this https://stackoverflow.com/a/12340289/342235:

No, actually, they are not. Even though they both call a method without parameters, one is a "method with zero parameter lists" while the other is a "method with one empty parameter list"

But I still not understand why hello would work

Community
  • 1
  • 1
Freewind
  • 193,756
  • 157
  • 432
  • 708

2 Answers2

3

Scala allows the omission of parentheses on methods of arity-0 (no arguments):

You should only omit the parenthesis when there are no side effects to the invokation though

http://docs.scala-lang.org/style/method-invocation.html

Oliver Shaw
  • 5,235
  • 4
  • 26
  • 35
  • Could you tell me more about the underlying? Why they say "No, actually, they are not (the same)."? – Freewind Aug 24 '14 at 17:09
  • Well interestingly (for me) var and def definitions live in the same namespace (according to the Odersky book). So there are some mechanisms I don't fully understand to resolve what you mean when you write `hello`. It could be you're looking for the `var`, the method with no params or the method with empty params. – Oliver Shaw Aug 24 '14 at 17:24
  • 2
    @Freewind: The "not the same" comment is about method definitions, not calls. – Chuck Aug 24 '14 at 17:41
0

As stated in Oliver Shaw's answer, Scala lets you leave out the parenthesis in functions with 0 arguments. As for why, it's likely to facilitate easy refactoring.

If you have a function that takes no arguments, and produces no side-effects, it's equivalent to an immutable value. If you always call such functions without parentheses, then you're free to change the underlying definition of the function to a value without having to refactor it everywhere it's referenced.

It's worth noting that val definitions are actually modeled as 0-arity methods in scala (unless specified with a private final beforehand).

Scala does something similar with its treatment of arity-1 functions defined on classes. You are allowed to omit the dot and the parenthesis. For example:

case class Foo(value: String) {
  def prepend(value2: String) = Foo(value2 + value)
}

Foo("one").prepend("two")
// is the same as...
Foo("one") prepend "two"

This is because Scala models all operators as arity-1 functions. You can rewrite 1 + 2 as 1.+(2) and have it mean the same thing. Representing operators as fully-fledged functions has some nice qualities. You can expect to pass an operator anywhere that you could pass a function, and the definition of the operator is actually defined for class instances (as opposed to a language like C#, where the infix operators are actually static methods that use special syntactic sugar to let them be represented as infix).

KChaloux
  • 3,918
  • 6
  • 37
  • 52