scala 中有 method_missing 吗? [英] Is there a method_missing in scala?

查看:52
本文介绍了scala 中有 method_missing 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于 Ruby 中的那个

similar to the one in Ruby

推荐答案

对于 [experimental] Scala 2.9 中的 Dynamic 特性,以下不再严格正确.例如,请参阅 Kipton Barros 的回答.

The following is no longer strictly true with the Dynamic trait found in [experimental] Scala 2.9. See the answer from Kipton Barros, for example.

然而,Dynamic 仍然不太method_missing,而是使用编译器魔法来有效地将方法调用重写为缺失"的方法,根据静态确定,到代理 (applyDynamic).从多态性的角度来看,静态确定缺失"方法的方法与 method_missing 不同:人们需要尝试动态转发(例如使用反射)获得真正的 method_missing 行为的方法.(当然这可以通过避免子类型来避免:-)

However, Dynamic is still not quite like method_missing, but rather employs compiler magic to effectively rewrite method calls to "missing" methods, as determined statically, to a proxy (applyDynamic). It is the approach of statically-determining the "missing" methods that differentiates it from method_missing from a polymorphism viewpoint: one would need to try and dynamically forward (e.g. with reflection) methods to get true method_missing behavior. (Of course this can be avoided by avoiding sub-types :-)

没有.Java 或 Scala 中不存在这样的概念.

和 Java 一样,Scala 中的所有方法在编译时都是绑定"的(这也决定了使用什么方法进行重载等).如果程序确实编译,则该方法存在(或根据编译器存在),否则不存在.这就是为什么您可以获得 NoSuchMethodError如果您更改类定义而不重建所有受影响的类.

Like Java, all the methods in Scala are 'bound' at compile time (this also determines what method is used for overloading, etc). If a program does compile, said method exists (or did according to the compiler), otherwise it does not. This is why you can get the NoSuchMethodError if you change a class definition without rebuilding all affected classes.

如果您只是担心尝试在符合签名的对象上调用方法(类型化鸭子类型"),那么也许您可以使用 结构类型.Scala 中的结构类型是对反射的神奇访问——因此它将绑定"推迟到运行时,并且可能会生成运行时错误.与 method_missing 不同,这不允许 target 处理错误,但它确实允许调用者(并且调用者理论上可以调用目标上定义的 methodMissing 方法......但这可能不是接触 Scala 的最佳方式.Scala 不是 Ruby :-)

If you are just worried about trying to call a method on an object which conforms to a signature ("typed duck typing"), then perhaps you may be able to get away with structural typing. Structural typing in Scala is magical access over reflection -- thus it defers the 'binding' until runtime and a runtime error may be generated. Unlike method_missing this does not allow the target to handle the error, but it does allow the caller to (and the caller could theoretically call a defined methodMissing method on the target... but this is probably not the best way to approach Scala. Scala is not Ruby :-)

这篇关于scala 中有 method_missing 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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