Enums in Logo

Our enum type `ServerState` has an underlying `integer` type.

```kotlin
enum class ServerState {
    StateIdle,
    StateConnected,
    StateError,
    StateRetrying
}

The possible values for ServerState are defined as constants. By using an enum class, each state is explicitly declared.

By implementing the toString method, the states can be printed out or converted to strings. Here is how you can achieve that in Kotlin:

enum class ServerState(private val stateName: String) {
    StateIdle("idle"),
    StateConnected("connected"),
    StateError("error"),
    StateRetrying("retrying");

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

If we have a value of type int (or Integer in Kotlin), we cannot directly pass it to functions expecting ServerState without explicit conversion. This provides some degree of compile-time type safety for enums.

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

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

fun transition(s: ServerState): ServerState {
    return when (s) {
        ServerState.StateIdle -> ServerState.StateConnected
        ServerState.StateConnected, ServerState.StateRetrying -> ServerState.StateIdle
        ServerState.StateError -> ServerState.StateError
        else -> throw IllegalArgumentException("unknown state: $s")
    }
}

To run the program, you can compile and execute it using Kotlin’s command-line tools or IDE support.

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

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