Main Page | See live article | Alphabetical index

Multiple dispatch

A feature of certain systems for object-oriented programming, such as the Common Lisp Object System, whereby a method can be specialized on more than one of its arguments.

In "conventional" object-oriented programming languages, when you invoke a method ("send a message" in Smalltalk, "call a member function" in C++) one of its arguments is treated specially and used to determine which of the (potentially many) methods of that name is to be applied. In languages with multiple dispatch, all the arguments are available for the run-time selection of which method to call.

This may be made clearer by an example. Imagine a game which has, among its (user-visible) objects, spaceships and asteroids. When two objects collide, the program may need to do different things according to what has just hit what.

In a language with only single dispatch, such as C++, the code would probably end up looking something like this:

  void Asteroid::collide_with(Thing * other) {
    Asteroid * other_asteroid = dynamic_cast(other);
    if (other_asteroid) {
      // deal with asteroid hitting asteroid
      return;
    }
    Spaceship * other_spaceship = dynamic_cast(other);
    if (other_spaceship) {
      // deal with asteroid hitting spaceship
      return;
    }
  }

with one collide_with member function for each kind of object that can collide with others, each containing one case per class. In a language with multiple dispatch, such as Common Lisp, it might look more like this:

  (defmethod collide-with ((x Asteroid) (y Asteroid))
    ;; deal with asteroid hitting asteroid
  )

(defmethod collide-with ((x Asteroid) (y Spaceship)) ;; deal with asteroid hitting spaceship )

and similarly for the other methods. No explicit testing or "dynamic casting" in sight.

In the presence of multiple dispatch, the traditional idea of methods as being defined in classes and contained in objects becomes less appealing -- each collide-with method there is attached to two different classes, not one. Hence, the special syntax for method invocation generally disappears, so that method invocation looks exactly like ordinary function invocation, and methods are grouped not in classes but in generic functions.

Multiple dispatch differs from overloading in C++ in that it takes place at run time, on the dynamic types of the arguments, rather at than compile time and on the static types of the arguments.