[SOLVED] Using a variable as a pattern in switch statements

In Actionscript 3 I could use constants and variables in switch statements. I’m having trouble porting my AS3 code that does this. I use a lot of constants because for me seeing a label instead of a value helps me remember the significance of that value without having to comment wherever that value is used.

Since as far as I can see, OpenFl/Haxe does not have a constant type I’m using variables whose labels start with a k. I’ve tried looking at Haxe Manual on pattern matching including variable capture and it didn’t help.

In AS3 I could write this:

    switch (aVar) {
        case k1: doSomething1(); break;
        case k2: doSomething2(); break;
        case k3: doSomething3(); break;

Besides removing the breaks, how do I rewrite that using k1, k2 and k2 and make it work?

Thanks in advance!

Haxe wants switch statements to be constant values.

You can, however, use variables if you use static inline, such as the following example:

public static inline var RED = "red";
public static inline var GREEN = "green";
public static inline var BLUE = "blue";


switch (color) {
    case RED: trace ("It's red!");
    case GREEN: trace ("It's green!");
    case BLUE: trace ("It's blue!");
    default: trace ("It's ... something!");

This is what we do for OpenFL values such as Event.COMPLETE

Thanks, that gives me back the ability to have constants which is important since I’m porting from AS3. Don’t understand why a constant type wasn’t created in Haxe to begin with.

I use a3hx to convert much of my AS3 code and then do some editing. Next task is to try to configure it to convert “const” to “static inline var” which will save me a lot of time.

Be aware that const to static inline var may work well in some cases, but may work poorly in others. For example, a constant String value is a good candidate for inlining, but an openfl.Vector object might not be something you want to inline (as it would create a new Vector instance each time it is referenced instead of keeping only one in memory)