Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What prevents a statically typed language from having something like Ruby's method_missing?

I don't have much experience with statically typed languages (currently learning Scala and loving it!) but one thing I've noticed is that they don't ever seem to have anything like Ruby's method_missing or ColdFusion's onMissingMethod. Is there some inherent limitation in statically typed languages that prevent or make this difficult?

like image 782
Dustin Martin Avatar asked Sep 24 '10 15:09

Dustin Martin


People also ask

Is Ruby a statically typed language?

Ruby is a dynamic language, which means that types are checked when the code is run. If you try to call a method on an object that does not exist, the compiler will not complain, you'll only find out about that error when the code is executed and you get a NoMethodError . Static languages avoid this problem.

What makes a language statically typed?

A statically-typed language is a language (such as Java, C, or C++) where variable types are known at compile time. In most of these languages, types must be expressly indicated by the programmer; in other cases (such as OCaml), type inference allows the programmer to not indicate their variable types.

Is Ruby strong or weak typed?

Ruby is "strong typed". Strong typing means an object's type (not in the OOP sense, but in a general sense) is checked before an operation requiring a certain type is executed on it. Ruby is "stronger" typed (with an "er") than most typical dynamic languages.

Does Ruby have dynamic typing?

Ruby is not only a dynamically but also strongly typed language, which means that it allows for a variable to change its type during runtime.


2 Answers

Certainly a mechanism for handling them could be added, but it is at odds with what static typing is: Compile-time determination that your program is free of type errors.

Addendum

Scala 2.9 introduced an experimental option enabling this sort of dynamic handling of accesses to types in ways that would otherwise fail static type checking. It was refined and made non-experimental in 2.10, though it is still controlled by a default-disable feature flag. You can read about it in the SIP 17 document. See SIP 18 for an explanation of Scala 2.10's "modularization" and feature flags.

like image 80
Randall Schulz Avatar answered Sep 29 '22 16:09

Randall Schulz


Scala version 2.9 introduces this functionality through the Dynamic trait (scaladoc). Classes that extend Dynamic get the magical method applyDynamic(methodName, args), which is analogous to Ruby's method_missing. As of Scala 2.9, the -Xexperimental option must be enabled to use Dynamic.

like image 23
Kipton Barros Avatar answered Sep 29 '22 17:09

Kipton Barros