3 ms·
Yep, it's just late binding. If you want that in the JVM, you can use Groovy, which does just that.
by brabel 5y ago
Yep, it's just late binding.
If you want that in the JVM, you can use Groovy, which does just that.
- brabel 5y agoExample: class Fire{} class Water {} class Grass {} class Ice {} def eff(Fire f, Grass g) { 'burn' } def eff(Fire f, Ice ice) { 'melt' } def eff(Water w, Grass g) { 'grow' } def eff(Water w, Ice ice) { 'freeze' } def eff(a, b) { 'undefined' } println eff(new Fire(), new Grass()) println eff(new Fire(), new Ice()) println eff(new Water(), new Grass()) println eff(new Water(), new Ice()) println eff(new Ice(), new Water()) Prints: burn melt grow freeze undefined
- pjmlp 5y agoThat is method overloading, which isn't the same as multi-dispatch.
- brabel 5y agoWhat would multi-dispatch do differently???
- adgjlsfhk1 5y agothe difference is that overloading works on compile time types but dispatch works on runtime types. This matters because when you write a generic algorithm, you don't know the type, so don't get the right behavior with overloading (you get the generic fallback).
- brabel 5y agoIn Groovy, dynamic dispatch is used. It's the runtime types that matter, as my example makes patently clear. EDIT: to make it even more obvious there's no difference: class Fire{} class Water {} class Grass {} class Ice {} def eff(Fire f, Grass g) { 'burn' } def eff(Fire f, Ice ice) { 'melt' } def eff(Water w, Grass g) { 'grow' } def eff(Water w, Ice ice) { 'freeze' } def eff(a, b) { 'undefined' } // hide compile-time types Object fire = new Fire() Object grass = new Grass() Object ice = new Ice() Object water = new Water() println eff(fire, grass) println eff(fire, ice) println eff(water, grass) println eff(water, ice) println eff(ice, water) Prints: burn melt grow freeze undefined
- ThomasMoll 5y agoGroovy supports multi-dispatch, if you needed to encapsulate a generic type, the compile would dynamically resolve that type correctly. See my example in Java (which has method overloading, but not MD)