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

前端 未结 3 1681
逝去的感伤
逝去的感伤 2020-11-27 12:57

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 o

相关标签:
3条回答
  • 2020-11-27 13:26

    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.

    0 讨论(0)
  • 2020-11-27 13:42

    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.

    0 讨论(0)
  • 2020-11-27 13:44

    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.

    0 讨论(0)
提交回复
热议问题