Programming Search⌘K

Patternadvanced

Double dispatch

Also called double dispatching, multiple polymorphism.

Double dispatch selects a method by the run-time types of two objects. In a single-dispatch language, the first call dispatches on the receiver, and it calls back the argument, which dispatches again.

Family
behavioral-design
Intent
Dispatch a call to different concrete functions depending on the run-time types of two objects, in a language whose calls dispatch on the receiver only.
Also called
multiple polymorphism

Intent

Double dispatch is a special form of multiple dispatch. It dispatches a function call to different concrete functions, depending on the run-time types of two objects that are involved in the call.1

Problem

In most object-oriented systems, the function that a call runs depends on the dynamic type of a single object, the receiver. These calls are single dispatch calls, or virtual function calls.1 Sometimes the correct computation depends on the types of two objects. In a game, the collision between a spaceship and an asteroid is computed differently from the collision between a spaceship and a space station.1 Other use cases are the sorting of a mixed set of objects, event handling that depends on the event type and the receiver type, and lock and key systems.1

Function overloading looks like a solution, but in C++ overloading is resolved at compile time. A call through a reference to Spaceship selects the overload for Spaceship, even when the object is an ApolloSpacecraft.1 Python's functools.singledispatch has the same limit at run time. The dispatch happens on the type of the first argument only:2

This code runs but gives a wrong answer on purpose.

from functools import singledispatch


class Ship: pass
class Asteroid: pass


@singledispatch
def collide(a, b):
    return "unknown"


@collide.register
def _(a: Ship, b):
    return "ship takes damage"  # the type of b is not known here


@collide.register
def _(a: Asteroid, b):
    return "asteroid hits something"  # the type of b is not known here


print(collide(Asteroid(), Ship()))
print(collide(Asteroid(), Asteroid()))  # meant: asteroids break apart
Output
asteroid hits something
asteroid hits something

Solution

Systems such as CLOS have multiple dispatch. In other systems, double dispatch is a way to get the same result with two single dispatches.1 The first call dispatches on the receiver. The receiver then calls a method of the argument and passes itself. The name of that second method tells the type of the first object, and the second call dispatches on the type of the argument.

  a.collide(b)                   first dispatch: on the type of a
     |
     +--> b.collide_with_asteroid(a)   if a is an Asteroid
     +--> b.collide_with_ship(a)       if a is a Ship
                 |
                 +--> second dispatch: on the type of b

In the C++ example of Wikipedia, each spaceship class gets a virtual function collideWith(Asteroid& asteroid) that calls asteroid.collideWith(*this). The type of *this is static in each class, so overloading now selects the correct function.1

Example

The example files show one program in each language. Ship and Asteroid each have collide, which calls back the other object with a method named for its own type. The program collides four pairs and prints:

ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
PythonGitHub
class Ship:
    name = "ship"

    def collide(self, other):
        return other.collide_with_ship(self)  # second dispatch, on other

    def collide_with_ship(self, ship):
        return "ships bounce"

    def collide_with_asteroid(self, asteroid):
        return "ship takes damage"


class Asteroid:
    name = "asteroid"

    def collide(self, other):
        return other.collide_with_asteroid(self)

    def collide_with_ship(self, ship):
        return "ship takes damage"

    def collide_with_asteroid(self, asteroid):
        return "asteroids break apart"


pairs = [(Ship(), Asteroid()), (Asteroid(), Ship()), (Asteroid(), Asteroid()), (Ship(), Ship())]
for a, b in pairs:
    print(f"{a.name} + {b.name}: {a.collide(b)}")
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. Python dispatches a method call on the receiver only, so collide calls back the other object. functools.singledispatch dispatches on the first argument only, so it does not give double dispatch.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct Ship;
struct Asteroid;

struct Body {
    virtual ~Body() = default;
    virtual std::string name() const = 0;
    virtual std::string collide(const Body& other) const = 0;
    virtual std::string collideWith(const Ship& ship) const = 0;
    virtual std::string collideWith(const Asteroid& asteroid) const = 0;
};

struct Ship : Body {
    std::string name() const override { return "ship"; }
    // *this has the static type Ship here, so the Ship overload is chosen
    std::string collide(const Body& other) const override { return other.collideWith(*this); }
    std::string collideWith(const Ship&) const override { return "ships bounce"; }
    std::string collideWith(const Asteroid&) const override { return "ship takes damage"; }
};

struct Asteroid : Body {
    std::string name() const override { return "asteroid"; }
    std::string collide(const Body& other) const override { return other.collideWith(*this); }
    std::string collideWith(const Ship&) const override { return "ship takes damage"; }
    std::string collideWith(const Asteroid&) const override { return "asteroids break apart"; }
};

int main() {
    std::vector<std::pair<std::unique_ptr<Body>, std::unique_ptr<Body>>> pairs;
    pairs.emplace_back(std::make_unique<Ship>(), std::make_unique<Asteroid>());
    pairs.emplace_back(std::make_unique<Asteroid>(), std::make_unique<Ship>());
    pairs.emplace_back(std::make_unique<Asteroid>(), std::make_unique<Asteroid>());
    pairs.emplace_back(std::make_unique<Ship>(), std::make_unique<Ship>());
    for (const auto& [a, b] : pairs) {
        std::cout << a->name() << " + " << b->name() << ": " << a->collide(*b) << "\n";
    }
}
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. The callbacks are overloads of collideWith. Inside each class the static type of *this is that class, so overload resolution picks the correct callback, and the virtual call picks the class of the argument.
JavaGitHub
interface Body {
    String name();
    String collide(Body other);
    String collideWithShip(Ship ship);
    String collideWithAsteroid(Asteroid asteroid);
}

class Ship implements Body {
    public String name() { return "ship"; }
    public String collide(Body other) { return other.collideWithShip(this); }
    public String collideWithShip(Ship ship) { return "ships bounce"; }
    public String collideWithAsteroid(Asteroid asteroid) { return "ship takes damage"; }
}

class Asteroid implements Body {
    public String name() { return "asteroid"; }
    public String collide(Body other) { return other.collideWithAsteroid(this); }
    public String collideWithShip(Ship ship) { return "ship takes damage"; }
    public String collideWithAsteroid(Asteroid asteroid) { return "asteroids break apart"; }
}

public class Main {
    public static void main(String[] args) {
        Body[][] pairs = {
            {new Ship(), new Asteroid()},
            {new Asteroid(), new Ship()},
            {new Asteroid(), new Asteroid()},
            {new Ship(), new Ship()},
        };
        for (Body[] p : pairs) {
            System.out.println(p[0].name() + " + " + p[1].name() + ": " + p[0].collide(p[1]));
        }
    }
}
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. The first call dispatches on the receiver, and the callback dispatches on the argument. The callbacks have different names, so no overload is chosen from a static type.
using System;

interface IBody
{
    string Name { get; }
    string Collide(IBody other);
    string CollideWithShip(Ship ship);
    string CollideWithAsteroid(Asteroid asteroid);
}

class Ship : IBody
{
    public string Name => "ship";
    public string Collide(IBody other) => other.CollideWithShip(this);
    public string CollideWithShip(Ship ship) => "ships bounce";
    public string CollideWithAsteroid(Asteroid asteroid) => "ship takes damage";
}

class Asteroid : IBody
{
    public string Name => "asteroid";
    public string Collide(IBody other) => other.CollideWithAsteroid(this);
    public string CollideWithShip(Ship ship) => "ship takes damage";
    public string CollideWithAsteroid(Asteroid asteroid) => "asteroids break apart";
}

class Program
{
    static void Main()
    {
        var pairs = new (IBody, IBody)[]
        {
            (new Ship(), new Asteroid()),
            (new Asteroid(), new Ship()),
            (new Asteroid(), new Asteroid()),
            (new Ship(), new Ship()),
        };
        foreach (var (a, b) in pairs)
        {
            Console.WriteLine($"{a.Name} + {b.Name}: {a.Collide(b)}");
        }
    }
}
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. This is the classic form with an interface. C# can also cast the argument to dynamic, which gives multiple dispatch without the callbacks.
JavaScriptGitHub
class Ship {
  get name() { return "ship"; }
  collide(other) { return other.collideWithShip(this); }
  collideWithShip(ship) { return "ships bounce"; }
  collideWithAsteroid(asteroid) { return "ship takes damage"; }
}

class Asteroid {
  get name() { return "asteroid"; }
  collide(other) { return other.collideWithAsteroid(this); }
  collideWithShip(ship) { return "ship takes damage"; }
  collideWithAsteroid(asteroid) { return "asteroids break apart"; }
}

const pairs = [
  [new Ship(), new Asteroid()],
  [new Asteroid(), new Ship()],
  [new Asteroid(), new Asteroid()],
  [new Ship(), new Ship()],
];
for (const [a, b] of pairs) {
  console.log(`${a.name} + ${b.name}: ${a.collide(b)}`);
}
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. A method call dispatches on the receiver, so collide calls back the other object with a method named for its own class.
TypeScriptGitHub
interface Body {
  name: string;
  collide(other: Body): string;
  collideWithShip(ship: Ship): string;
  collideWithAsteroid(asteroid: Asteroid): string;
}

class Ship implements Body {
  name = "ship";
  collide(other: Body): string { return other.collideWithShip(this); }
  collideWithShip(_ship: Ship): string { return "ships bounce"; }
  collideWithAsteroid(_asteroid: Asteroid): string { return "ship takes damage"; }
}

class Asteroid implements Body {
  name = "asteroid";
  collide(other: Body): string { return other.collideWithAsteroid(this); }
  collideWithShip(_ship: Ship): string { return "ship takes damage"; }
  collideWithAsteroid(_asteroid: Asteroid): string { return "asteroids break apart"; }
}

const pairs: [Body, Body][] = [
  [new Ship(), new Asteroid()],
  [new Asteroid(), new Ship()],
  [new Asteroid(), new Asteroid()],
  [new Ship(), new Ship()],
];
for (const [a, b] of pairs) {
  console.log(`${a.name} + ${b.name}: ${a.collide(b)}`);
}
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. The interface Body lists one callback method for each class, and each class implements all of them.
package main

import "fmt"

type Body interface {
	Name() string
	Collide(other Body) string
	CollideWithShip(s Ship) string
	CollideWithAsteroid(a Asteroid) string
}

type Ship struct{}

func (Ship) Name() string                     { return "ship" }
func (s Ship) Collide(other Body) string      { return other.CollideWithShip(s) }
func (Ship) CollideWithShip(Ship) string      { return "ships bounce" }
func (Ship) CollideWithAsteroid(Asteroid) string { return "ship takes damage" }

type Asteroid struct{}

func (Asteroid) Name() string                     { return "asteroid" }
func (a Asteroid) Collide(other Body) string      { return other.CollideWithAsteroid(a) }
func (Asteroid) CollideWithShip(Ship) string      { return "ship takes damage" }
func (Asteroid) CollideWithAsteroid(Asteroid) string { return "asteroids break apart" }

func main() {
	pairs := [][2]Body{{Ship{}, Asteroid{}}, {Asteroid{}, Ship{}}, {Asteroid{}, Asteroid{}}, {Ship{}, Ship{}}}
	for _, p := range pairs {
		fmt.Printf("%s + %s: %s\n", p[0].Name(), p[1].Name(), p[0].Collide(p[1]))
	}
}
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. Go has no overloading, so each callback has its own name. Another form is a type switch on both values.
RustGitHub
trait Body {
    fn name(&self) -> &'static str;
    fn collide(&self, other: &dyn Body) -> &'static str;
    fn collide_with_ship(&self) -> &'static str;
    fn collide_with_asteroid(&self) -> &'static str;
}

struct Ship;
struct Asteroid;

impl Body for Ship {
    fn name(&self) -> &'static str { "ship" }
    fn collide(&self, other: &dyn Body) -> &'static str { other.collide_with_ship() }
    fn collide_with_ship(&self) -> &'static str { "ships bounce" }
    fn collide_with_asteroid(&self) -> &'static str { "ship takes damage" }
}

impl Body for Asteroid {
    fn name(&self) -> &'static str { "asteroid" }
    fn collide(&self, other: &dyn Body) -> &'static str { other.collide_with_asteroid() }
    fn collide_with_ship(&self) -> &'static str { "ship takes damage" }
    fn collide_with_asteroid(&self) -> &'static str { "asteroids break apart" }
}

fn main() {
    let pairs: [(&dyn Body, &dyn Body); 4] =
        [(&Ship, &Asteroid), (&Asteroid, &Ship), (&Asteroid, &Asteroid), (&Ship, &Ship)];
    for (a, b) in pairs {
        println!("{} + {}: {}", a.name(), b.name(), a.collide(b));
    }
}
Output
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
  • Verdict: idiom. Trait objects dispatch on the receiver, so collide calls back the other trait object. Another form, for a closed set of types, is an enum and one match on the pair (a, b).

Consequences

The benefits:

  • The choice of computation depends on the run-time types of both arguments, with no type tests in the client.1

The costs:

  • Run-time cost. The call has the usual costs of dynamic resolution, usually more than in a language with single dispatch only.1
  • Many methods. In the example, each class has one callback method for each class that it can meet. A third class, such as a space station, adds a callback method to each existing class.
  • Order. The two objects of a call have different roles. In the example, ship + asteroid and asteroid + ship must give the same result, so two methods must agree.

When not to use it

  • The language has multiple dispatch, for example CLOS.1 Then one method can be declared for each pair of types.
  • In C#, a call can do multiple dispatch without the Visitor pattern: the method uses traditional polymorphism and casts the argument to dynamic.1
  • Only one of the two types varies. Then single dispatch on that object is sufficient.
  • Visitor. The problem of the C++ example can be resolved by simulating double dispatch, for example with the Visitor pattern.1
  • Reflected operators in Python. To evaluate x - y, Python calls type(y).__rsub__(y, x) if type(x).__sub__(x, y) returns NotImplemented, or if type(y) is a subclass of type(x).3 So a binary operator can dispatch first on the left operand and then on the right operand:
class Meters:
    def __init__(self, n):
        self.n = n

    def __add__(self, other):
        if isinstance(other, Meters):
            return Meters(self.n + other.n)
        if isinstance(other, int):
            return Meters(self.n + other)
        return NotImplemented

    __radd__ = __add__

    def __repr__(self):
        return f"Meters({self.n})"


print(Meters(2) + 3)  # Meters.__add__
print(3 + Meters(2))  # int.__add__ returns NotImplemented, then Meters.__radd__
print(sum([Meters(1), Meters(2)]))  # sum starts with 0 + Meters(1)
Output
Meters(5)
Meters(5)
Meters(3)

Known uses

  • Dan Ingalls described double dispatching in Smalltalk in 1986.1
  • CPython's fractions.Fraction makes its arithmetic operators with _operator_fallbacks, which returns a forward and a reverse function. The comment says that mixed-mode operations should "call an implementation whose author knew about the types of both arguments", or convert both to the nearest built in type. The functions return NotImplemented for types that they do not know.4

References

  1. Double dispatch, Wikipedia, Introduction; Overview; Use cases; A common idiom; Examples, C++ and C#
  2. The Python Standard Library, functools, functools.singledispatch, functools.singledispatch
  3. The Python Language Reference, 3.3.8 Emulating numeric types, object.__radd__ and the other reflected methods
  4. CPython v3.14.0 source, Lib/fractions.py, Fraction._operator_fallbacks, forward and reverse, lines 616 to 724

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/VEMJGW/text.yaml