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.
As you already stated in your question, you simply define it by defining a method (not a function) called
apply.gets translated to
So, as long as
foohas anapplymethod of correct arity and type, this will work.Some examples of implementations of the
applymethod are theArraycompanion object, which allows you to construct an array by callingArray(1, 2, 3)(which is actually justArray.apply(1, 2, 3)) and theArrayclass, which allows you to access an array element by callinganArray(i)(which is actually justanArray.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 formfoo.(bar, baz)gets translated tofoo.call(bar, baz).A similar method is
update:gets translated to