Enums in Kotlin

Enumerated types (enums) are a special case of sum types. An enum is a type that has a fixed number of possible values, each with a distinct name. Kotlin has a dedicated enum class feature for implementing enums.

Our enum type ServerState is defined using Kotlin’s enum class.

enum class ServerState {
    Idle,
    Connected,
    Error,
    Retrying
}

You can associate a string representation with each enum value by overriding the toString method.

enum class ServerState(val state: String) {
    Idle("idle"),
    Connected("connected"),
    Error("error"),
    Retrying("retrying");

    override fun toString(): String {
        return state
    }
}

If we have a value of type Int, we need to ensure we don’t pass it directly to functions expecting a ServerState. This provides some degree of compile-time type safety for enums.

Here’s how you could write the main function in Kotlin:

fun main() {
    val ns = transition(ServerState.Idle)
    println(ns)

    val ns2 = transition(ns)
    println(ns2)
}

transition emulates a state transition for a server; it takes the existing state and returns a new state:

fun transition(s: ServerState): ServerState {
    return when (s) {
        ServerState.Idle -> ServerState.Connected
        ServerState.Connected, ServerState.Retrying -> ServerState.Idle
        ServerState.Error -> ServerState.Error
        else -> throw IllegalArgumentException("Unknown state: $s")
    }
}

To run the program, execute the Kotlin code.

$ kotlinc main.kt -include-runtime -d main.jar
$ java -jar main.jar
connected
idle

In this example, we define an enum class to represent the server state, associate string values with each state, and implement state transitions. Kotlin provides built-in support for enums, making them easy to use and read.