How does Scala's apply() method magic work?
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.
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.
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.