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

E01010 — EK9 uses separate parameter lines. Mark the base method 'as dispatcher' with both parameters.

Incorrect:

      combine(Shape s1, Shape s2)

Correct:

      combine() as dispatcher
        ->
          s1 as Shape
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: visitor, dispatcher, double dispatch, two parameter, multi-dispatch