Time for action – Switching over enums with parameters

Switching over an enum that has parameters is done in the same way as switching over a basic enum. The only difference is that we will have to write the names of the parameters in order to get them.

Imagine that we have an enum representing a color either as RGB or RGBA and that we want to get the string representing this color.

  1. First, let's write our enum:
    enum Color
    {
       rgb(r : Int, g : Int, b : Int);
       rgba(r : Int, g : Int, b : Int, a : Int);
    }
  2. Now, let's write our switch:
       public static function fromColorToString(color :Color)
       {
          switch(color)
          {
             case rgb(r, g, b):
                return "RGB(" + r + "," + g + ", " + b + ")";
             case rgba(r, g, b, a):
                return "RGB(" + r + "," + g + ", " + b + "," + a + ")";
          }
       }

What ...

Get haXe 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.