Do all dynamically typed languages not support function overloading? If the answer is yes, then why is that?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
The issue is easier to understand if you consider carefully what it really means to overload a function.
Overloaded methods e.g. in Java are really two completely separate entities; they share no byte code, no address, nothing except their name; and their name isn't really the same either, since in the compiler symbol table, a
print() method for
ints and a
Strings actually have a mangled name that contains both the user-visible identifier ("print") and additional information encoding the argument type.
print() function really is called
The details vary a bit from language to language, but the gist is, if you don't have an explicit representation of data types in your compile-time/run-time system, you can't use them to tell elements of the system apart, and that is why overloading on types is largely restricted to systems with a strong presence of types in the language definition.
Dynamically typed languages may use double dispatch (https://en.m.wikipedia.org/wiki/Double_dispatch) to implement functions that depend on an argument's type.
For example, in Smalltalk there is a method
print: anObject defined in class Stream that defers the actual implementation of how an object should be printed to the argument:
print: anObject anObject printOn: self
If the implementation depends on the types of both recipient and argument (for example in the numeric classes for mixed arithmetics) the indirect method would be specific to the original receiver's class, so the method
+ in class
Integer could look like this:
+ aNumber ^aNumber addToInteger: self
where different numeric classes implement
Additional to other answers, there are dynamically typed languages where you can overload functions with different number of arguments (a.k.a "arity"). For example, there is erlang:
add(X,Y) -> Z = X+Y, io:fwrite("~w~n",[Z]). add(X,Y,Z) -> A = X+Y+Z, io:fwrite("~w~n",[A]).
Method overloading and overriding are both mechanisms where the language select between multiple function/method implementation with the same name. According to the most common definition, overloading is resolved at compile-time depending on the static types and number of arguments, while overriding (also known is dynamic dispatch) is resolved at runtime.
So almost by definition, dynamic languages would not support overloading, since it is static, not dynamic.