tags:

views:

845

answers:

3

In Scala, if I define a method called apply in a class or a top-level object, that method will be called whenever I append a pair a parentheses to an instance of that class, and put the appropriate arguments for apply() in between them. e.g.,

class Foo(x: Int) {
  def apply(y: Int) = {
    x*x + y*y
  }
}

val f = new Foo(3)
f(4)   // returns 25

So basically, < object >(< args >) is just syntactic sugar for < object >.apply(< args >). But here's my question: how does Scala do this conversion? Is there a globally defined implicit conversion going on here, similar to the implicit type conversions in the Predef object (but different in kind)? Or is it some deeper magic? I ask because it seems like Scala strongly favors consistent application of a smaller set of rules, rather than many rules with many exceptions. This initially seems like an exception to me, but I thought I'd ask to see if anyone with a deeper understanding of the language could explain to me how this fits in.

+1  A: 

It is actually the other way around, an object or class with an apply method is the normal case and a function is way to construct implicitly an object of the same name with an apply method. Actually every function you define is an subobject of the Functionn trait (n is the number of arguments).

Refer to page 136 of the Scala Language Specification for more information of the topic.

sebasgo
+7  A: 

I don't think there's anything deeper going on that what you have originally said: it's just syntactic sugar whereby the compiler converts f(a) into f.apply(a) as a special syntax case.

this might seem like a specific rule but only a few of these (e.g. with update) allows for DSL-like constructs and libraries.

oxbow_lakes
If you swap f(a) and f.apply(a) it is correct ;)
sebasgo
I think I was right the first time ;-P
oxbow_lakes
I'd add "when `f` is an object (including functions)". When `f` is a method, there is obviously no such translation.
Alexey Romanov
A: 

I ask because it seems like Scala strongly favors consistent application of a smaller set of rules, rather than many rules with many exceptions.

Yes. And this rule belongs to this smaller set.

Alexey Romanov