0

Possible Duplicate:
How does Scala's apply() method magic work?

I am an absolute beginner in Scala and after reading in one of the Scala books that apply function is like "overloaded () operator" I began to wonder how tha is defined. Namely an operator () would take the argument between the brackets themselves, rather than in the conventional infix a () b notation. Is definition of such operator possible in Scala and if so, what is the definition syntax? Thanks.

Community
  • 1
  • 1
Bober02
  • 15,034
  • 31
  • 92
  • 178

1 Answers1

3

As you already stated in your question, you simply define it by defining a method (not a function) called apply.

foo(bar, baz)

gets translated to

foo.apply(bar, baz)

So, as long as foo has an apply method of correct arity and type, this will work.

Some examples of implementations of the apply method are the Array companion object, which allows you to construct an array by calling Array(1, 2, 3) (which is actually just Array.apply(1, 2, 3)) and the Array class, which allows you to access an array element by calling anArray(i) (which is actually just anArray.apply(i)).

This is similar to e.g. Python, where function calls get translated into calls to the __call__ operator or Ruby, where an expression of the form foo.(bar, baz) gets translated to foo.call(bar, baz).

A similar method is update:

foo(bar) = baz

gets translated to

foo.update(bar, baz)
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653