Scala 的 apply() 方法魔法是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1223834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does Scala's apply() method magic work?
提问by Jeff
In Scala, if I define a method called applyin 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:
在 Scala 中,如果我定义了一个apply在类或顶级对象中调用的方法,那么每当我将一对括号附加到该类的实例并apply()在它们之间放置适当的参数时,就会调用该方法。例如:
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).
所以基本上,object(args)只是object.apply(args).
How does Scala do this conversion?
Scala 是如何进行这种转换的?
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.
这里是否存在全局定义的隐式转换,类似于 Predef 对象中的隐式类型转换(但种类不同)?或者是某种更深层次的魔法?我问是因为 Scala 似乎强烈支持一组较小的规则的一致应用,而不是具有许多例外的许多规则。这最初对我来说似乎是一个例外。
采纳答案by oxbow_lakes
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.
我认为没有比您最初所说的更深入的事情了:这只是语法糖,编译器将其f(a)转换f.apply(a)为特殊的语法情况。
This might seem like a specific rule, but only a few of these (for example, with update) allows for DSL-like constructs and libraries.
这可能看起来像是一个特定的规则,但只有少数规则(例如, with update)允许类似DSL的构造和库。
回答by sebasgo
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 Functionntrait (n is the number of arguments).
它实际上是相反的,具有 apply 方法的对象或类是正常情况,而函数是使用 apply 方法隐式构造同名对象的方法。实际上,您定义的每个函数都是 Function n特征的子对象(n 是参数的数量)。
Refer to section 6.6:Function Applicationsof the Scala Language Specificationfor more information of the topic.
请参见6.6:功能应用的的斯卡拉语言规范为主题的更多信息。
回答by Alexey Romanov
I ask because it seems like Scala strongly favors consistent application of a smaller set of rules, rather than many rules with many exceptions.
我问是因为 Scala 似乎强烈支持一组较小的规则的一致应用,而不是具有许多例外的许多规则。
Yes. And this rule belongs to this smaller set.
是的。而这条规则属于这个较小的集合。

