Enums in R Programming Language

Our enum type ServerState 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. See this post for a longer explanation.

If we have a value of 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.


Here is how we’d represent the code in Java:

import java.util.HashMap;
import java.util.Map;

enum ServerState {
    StateIdle,
    StateConnected,
    StateError,
    StateRetrying;
}

public class Main {

    private static final Map<ServerState, String> stateName;
    
    static {
        stateName = new HashMap<>();
        stateName.put(ServerState.StateIdle, "idle");
        stateName.put(ServerState.StateConnected, "connected");
        stateName.put(ServerState.StateError, "error");
        stateName.put(ServerState.StateRetrying, "retrying");
    }

    public static void main(String[] args) {
        ServerState ns = transition(ServerState.StateIdle);
        System.out.println(ns); // connected
        ServerState ns2 = transition(ns);
        System.out.println(ns2); // idle
    }

    static ServerState transition(ServerState s) {
        switch (s) {
            case StateIdle:
                return ServerState.StateConnected;
            case StateConnected:
            case StateRetrying:
                return ServerState.StateIdle;
            case StateError:
                return ServerState.StateError;
            default:
                throw new IllegalStateException("Unknown state: " + s);
        }
    }
}

Explanation:

  • Enum Declaration: In Java, enums are a special type of class that represents a group of constants. Here, ServerState enum contains the states.

  • State Names Mapping: We are using a static HashMap to map enum values to their string representations. This is akin to the map you saw in the original example.

  • String Representation: In Java, every enum has a built-in toString method that can be overridden if necessary, but we are using a map to associate specific string values in this example.

  • Transition Function: The transition function takes the current state and returns the next state based on some logic, similar to the switch-case structure.

You can run this Java program by compiling the code into a .class file and then using java to execute it.

$ javac Main.java
$ java Main
connected
idle

Now that we can run and build basic Java programs, let’s learn more about the language.