How does Scala's apply() method magic work?
Asked Answered
C

3

79

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. For example:

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).

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.

Contemporary answered 3/8, 2009 at 18:18 Comment(1)
Very great explanation, stackoverflow.com/questions/9737352/#9738862Profligate
S
67

I don't think there's anything deeper going on than 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 (for example, with update) allows for DSL-like constructs and libraries.

Soemba answered 3/8, 2009 at 18:33 Comment(2)
I'd add "when f is an object (including functions)". When f is a method, there is obviously no such translation.Supreme
@AlexeyRomanov: Well, if f is a method that is defined without a parameter list, then f(a) is indeed interpreted as something like val _tmp = f; _tmp.apply(a). But that's really getting firmly into the splitting-of-hairs territory.Lastminute
A
20

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 section 6.6:Function Applications of the Scala Language Specification for more information of the topic.

Annabelleannabergite answered 3/8, 2009 at 18:28 Comment(1)
+1 for changing the Scala Language Specification. I added the right location since your page number is outdated.Ashurbanipal
S
8

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.

Supreme answered 3/8, 2009 at 21:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.