Scala 的 apply() 方法魔法是如何工作的? [英] How does Scala's apply() method magic work?

查看:63
本文介绍了Scala 的 apply() 方法魔法是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,如果我在类或顶级对象中定义了一个名为 apply 的方法,那么每当我将一对括号附加到该类的实例时,就会调用该方法,并且将 apply() 的适当参数放在它们之间.例如:

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

所以基本上,object(args) 只是 object.apply(args) 的语法糖.

So basically, object(args) is just syntactic sugar for object.apply(args).

Scala 如何进行这种转换?

How does Scala do this conversion?

这里是否进行了全局定义的隐式转换,类似于 Predef 对象中的隐式类型转换(但种类不同)?或者是某种更深层次的魔法?我问是因为 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.

推荐答案

我认为没有什么比您最初所说的更深入的了:这只是编译器转换 f(a)<的语法糖/code> 到 f.apply(a) 作为特殊的语法案例.

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.

这似乎是一个特定的规则,但其中只有少数规则(例如,使用 update)允许 DSL 类结构和库.

This might seem like a specific rule, but only a few of these (for example, with update) allows for DSL-like constructs and libraries.

这篇关于Scala 的 apply() 方法魔法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆