Book Image

haXe 2 Beginner's Guide

5 (1)
Book Image

haXe 2 Beginner's Guide

5 (1)

Overview of this book

Table of Contents (21 chapters)
haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 just happened?

In the second step, we got parameters from the color so that we could construct the string.

As you can see, you don't need to rewrite the types of the parameters...