问题
similar to the one in Ruby
回答1:
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.
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 :-)
No. Such a concept does not exist in Java or Scala.
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.
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 :-)
回答2:
Yes, as of Scala 2.9 with the -Xexperimental
option, one can use the Dynamic
trait
(scaladoc). Classes that extend Dynamic
get the magical method applyDynamic(methodName, args)
which behaves like Ruby's method_missing
.
Among other things, the Dynamic
trait can be useful for interfacing with dynamic languages on the JVM.
回答3:
Not really. It doesn't make sense. Scala is a statically-typed language in which methods are bound at compile time; Ruby is a dynamically-typed language in which messages are passed to objects, and these messages are evaluated at runtime, which allows Ruby to handle messages that it doesn't directly respond to, à la method_missing
.
You can mimic method_missing
in a few ways in Scala, notably by using the Actors library, but it's not quite the same (or nearly as easy) as Ruby's method_missing
.
回答4:
No, this is not possible in Scala 2.8 and earlier.
来源:https://stackoverflow.com/questions/3105594/is-there-a-method-missing-in-scala