Dispatcher for type switching: the dispatcher version

The complete source of forAI_dispatcher_after.ek9, compiled by the EK9 compiler. Shown on forAI.html.

#!ek9
defines module site.forAI.dispatchafter

  defines constant
    PI <- 3.14159

  defines class

    Shape as abstract
      default operator ?

    Circle extends Shape
      radius as Float: Float()

      Circle()
        -> radius as Float
        this.radius :=: radius

      radius() as pure
        <- rtn as Float: radius

      default operator ?

    Square extends Shape
      side as Float: Float()

      Square()
        -> side as Float
        this.side :=: side

      side() as pure
        <- rtn as Float: side

      default operator ?

    Triangle extends Shape
      base as Float: Float()
      height as Float: Float()

      Triangle()
        ->
          base as Float
          height as Float
        this.base :=: base
        this.height :=: height

      base() as pure
        <- rtn as Float: base

      height() as pure
        <- rtn as Float: height

      default operator ?

    //A dispatcher is a METHOD - declare it in a class
    AreaCalculator
      calculateArea() as dispatcher
        -> shape as Shape
        <- area as Float: 0.0

      calculateArea()
        -> circle as Circle
        <- area as Float: PI * circle.radius() * circle.radius()

      calculateArea()
        -> square as Square
        <- area as Float: square.side() * square.side()

      calculateArea()
        -> triangle as Triangle
        <- area as Float: 0.5 * triangle.base() * triangle.height()

  defines program

    Areas()
      stdout <- Stdout()
      calculator <- AreaCalculator()
      shapes as List of Shape: [Square(2.0), Circle(2.0), Triangle(base: 3.0, height: 4.0)]
      for shape in shapes
        stdout.println($calculator.calculateArea(shape))

Download forAI_dispatcher_after.ek9

Output

4.0
12.56636
6.0