Dispatcher for type switching: the switch version

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

#!ek9
defines module site.forAI.dispatchbefore

  defines class

    Shape
      kind as String: String()
      size as Float: Float()

      Shape()
        ->
          kind as String
          size as Float
        this.kind :=: kind
        this.size :=: size

      type() as pure
        <- rtn as String: kind

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

      default operator ?

  defines function

    calculateCircleArea() as pure
      -> shape as Shape
      <- area as Float: 3.14159 * shape.size() * shape.size()

    calculateSquareArea() as pure
      -> shape as Shape
      <- area as Float: shape.size() * shape.size()

    calculateTriangleArea() as pure
      -> shape as Shape
      <- area as Float: 0.5 * shape.size() * shape.size()

    processShape()
      -> shape as Shape
      <- area as Float?

      switch shape.type()
        case "circle"
          area: calculateCircleArea(shape)
        case "square"
          area: calculateSquareArea(shape)
        case "triangle"
          area: calculateTriangleArea(shape)
        default
          area: 0.0

  defines program

    AreaOfASquare()
      stdout <- Stdout()
      stdout.println($processShape(Shape("square", 2.0)))

Download forAI_dispatcher_before.ek9

Output

4.0