Enums in ActionScript
Our ServerState
enum type has an underlying int
type.
The possible values for ServerState
are defined as constants. The special keyword iota
generates successive constant values automatically; in this case 0, 1, 2 and so on.
By implementing the fmt.Stringer
interface, values of ServerState
can be printed out or converted to strings.
This can get cumbersome if there are many possible values. In such cases, the stringer tool
can be used in conjunction with go:generate
to automate the process.
If we have a value of the type int
, we cannot pass it to transition
- the compiler will complain about type mismatch. This provides some degree of compile-time type safety for enums.
transition
emulates a state transition for a server; it takes the existing state and returns a new state.
package {
import flash.display.Sprite;
import flash.events.Event;
public class ServerStateExample extends Sprite {
// Enum values for ServerState.
public static const StateIdle:int = 0;
public static const StateConnected:int = 1;
public static const StateError:int = 2;
public static const StateRetrying:int = 3;
// Mapping state to string representation.
private static var stateName:Object = {
0: "idle",
1: "connected",
2: "error",
3: "retrying"
};
public function ServerStateExample() {
var ns:int = transition(StateIdle);
trace(stateToString(ns));
var ns2:int = transition(ns);
trace(stateToString(ns2));
}
// Function to return the string representation of the state.
public static function stateToString(ss:int):String {
return stateName[ss] || "unknown state";
}
// Function to emulate state transition.
public static function transition(s:int):int {
switch(s) {
case StateIdle:
return StateConnected;
case StateConnected:
case StateRetrying:
return StateIdle;
case StateError:
return StateError;
default:
throw new Error("unknown state: " + s);
}
}
}
}
To run the program, compile the code and execute it within an environment that supports ActionScript, such as Adobe Flash Player or Apache Royale.
$ mxmlc ServerStateExample.as
# This will compile the ActionScript code into a SWF file.
By implementing the mapping and transition function, you ensure that the enum values can be converted to strings and help in transitioning between states, providing safety against type mismatches. The above example shows how to define and use enums in ActionScript with proper state management and conversion to and from string representations.