Dispatch on two parameters to handle different shape combinations.

← Design Patterns and Idioms · Ref: Q1124

Multi-parameter dispatch -- parameter order matters:

  combine() as dispatcher
    ->
      s1 as Shape
      s2 as Shape
    <- rtn as String: "Generic"
  combine()
    ->
      s1 as Circle
      s2 as Circle
    <- rtn as String: "Circle-Circle"

Circle+Rectangle has a handler but Rectangle+Circle falls through to generic.

See Q1121 for single-param dispatch. See Q1123 for deep hierarchy.

Example

defines module qa.designpatterns.dispatchertwoparam

  defines class

    Shape as abstract
      default operator ?

    Circle is Shape
      default operator ?

    Rectangle is Shape
      default operator ?

    Combiner

      combine() as dispatcher
        ->
          s1 as Shape
          s2 as Shape
        <- rtn as String: "Generic"

      combine()
        ->
          s1 as Circle
          s2 as Circle
        <- rtn as String: "Circle-Circle"

      combine()
        ->
          s1 as Circle
          s2 as Rectangle
        <- rtn as String: "Circle-Rectangle"

  defines program

    DispatcherTwoParamDemo()
      stdout <- Stdout()
      combiner <- Combiner()

      circle <- Circle()
      rectangle <- Rectangle()

      stdout.println(combiner.combine(circle, circle))
      stdout.println(combiner.combine(circle, rectangle))
      //Rectangle+Circle has no specific handler — falls to Generic
      stdout.println(combiner.combine(rectangle, circle))

Common mistakes

E02030 — Each handler is chosen by its parameter types, so two handlers with the same types are duplicate/ambiguous methods and the compiler rejects them with E02030. See ek9 -h E02030 for details.

Incorrect:

          s1 as Circle
          s2 as Circle

Correct:

          s1 as Circle
          s2 as Rectangle
Other ways to ask this
  • I need to handle Circle+Circle differently from Circle+Rectangle interactions
  • In Java I'd use the visitor pattern for double dispatch. Write the EK9 two-param dispatcher
  • Given two Shape parameters, select the correct handler based on both runtime types
  • Set up a dispatcher that dispatches on two parameter types simultaneously

Coming from another language?

Java: double dispatch via visitor pattern (complex). Kotlin: no built-in. EK9: two-param dispatcher — direct multi-dispatch without visitor boilerplate.

Keywords: double dispatch, dispatcher, visitor, multi-dispatch, two parameter