Double dispatch (source code)

= Double dispatch
{wiki}

<Double dispatch> selects behavior using the <runtime types> of two participating <software objects>, often by arranging two ordinary <dynamic dispatch> steps. The <visitor pattern> supplies a useful example.

Suppose `Shape` has an overridable `accept(Renderer)` operation, and `Renderer` has overridable overloads `visit(Circle)` and `visit(Rectangle)`. A `Circle` implementation of `accept` calls `renderer.visit(this)`. Calling `shape.accept(renderer)` first selects `Circle.accept` using the shape's <runtime type>. Inside that method, `this` has the <static type> `Circle` because the method is defined in the `Circle` <software class>. <Method overloading> therefore chooses the `visit(Circle)` signature. The renderer's <runtime type> then selects the implementation of that signature.

The result depends on both the concrete shape and concrete renderer. Ordinary <method overloading> alone would not inspect an argument's <runtime type> to choose the shape overload. The <static type> established in the first dispatched method is the bridge to the second dispatch.<Scala 2.11 expressions specification>[Overloading Resolution, static argument typing; example uses ordinary overridable instance methods]{ref}