In languages like Scala, one can have multiple definitions for one method name by changing the number of parameters and/or the type of the parameters of the method. This is called method overloading.
How is that different from multiple dispatch?
Thank you
In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature.
Polymorphism is the process to define more than one body for functions/methods with same name. Overloading IS a type of polymorphism, where the signature part must be different. Overriding is another, that is used in case of inheritance where signature part is also same.
Overloading occurs between the methods in the same class. Overriding methods have the same signature i.e. same name and method arguments. Overloaded method names are the same but the parameters are different. With Overloading, the method to call is determined at the compile-time.
Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch.
Method overloading is resolved at compile time.
Multiple dispatch is resolved at runtime.
When using double dispatch the called method depends on the actual type of receiver and arguments. Method overloading however, only allows the called method to depend on the declared type of the parameters. Why? Java binds method calls at compile time with their full signature (early binding). The full signature includes all parameter types, hence when the actual type of an argument differs at runtime (polymoprhism), overloading does not work as you might expect!
void add(Foo o) { ... } void add(Bar o) { ... } void client() { Foo o = new Bar(); add(o); // calls add(Foo) not add(Bar)! }
using multiple dispatch however
void add(Foo o) { o.dispatch(this); } void add(Bar o) { o.dispatch(this); } void client() { Foo o = new Bar(); add(o); // calls #dispatch as defined in Bar! }
Things might slightly differ in Scala, though the general distinction should be the same as presented here in all programming languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With