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

ScalaSyntactic SugarMagic MethodsCompanion Object

Scala Problem Overview


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.

Scala Solutions


Solution 1 - Scala

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.

Solution 2 - Scala

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.

Solution 3 - Scala

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffView Question on Stackoverflow
Solution 1 - Scalaoxbow_lakesView Answer on Stackoverflow
Solution 2 - ScalasebasgoView Answer on Stackoverflow
Solution 3 - ScalaAlexey RomanovView Answer on Stackoverflow