Enums in Clojure
Our enum-like type ServerState
has an underlying int
type. In Clojure, we’ll use the keyword type to represent the different states a server can be in.
The possible values for ServerState
are defined as constants:
Implementing a Stringer-like function in Clojure can be done using a simple map lookup:
Next, our main function will emulate a state transition for a server; it takes the existing state and returns a new state:
Finally, to see our state transitions in action, we can define a main function:
You can run the program using the following command:
Here’s what the output would look like:
In summary, this example demonstrates how to create and use enum-like constructs in Clojure by leveraging keywords and maps. Now that we understand how to create state transitions, let’s explore more features of the language.