Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between multiple dispatch and method overloading?

Tags:

oop

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

like image 470
gnuvince Avatar asked Nov 26 '09 02:11

gnuvince


People also ask

What is the difference between method overloading and method overloading?

In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature.

What is difference between method overloading and polymorphism?

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.

What is method overloading and overriding and what is difference between two?

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.

What is multiple dispatch in Julia?

Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch.


1 Answers

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.

like image 185
akuhn Avatar answered Sep 23 '22 20:09

akuhn