Kotlin Enum Classes

Kotlin Enum Class

In Kotlin, you can define enum classes, which are a special type of class used to represent a fixed set of constants or values.

Enum classes are a way to create named constants and provide a type-safe alternative to using integers or strings for representing a set of related values.

Example 1: Basic example for Enum class

In this example, Color is an enum class with three constant values: RED, GREEN, and BLUE. You can use these values in your code like this:

Kotlin Program

enum class Color {
    RED, GREEN, BLUE
}

fun main() {
    val selectedColor: Color = Color.GREEN

    when (selectedColor) {
        Color.RED -> println("Selected color is red")
        Color.GREEN -> println("Selected color is green")
        Color.BLUE -> println("Selected color is blue")
    }
}

Output

Selected color is green

Enum class with properties, and methods

In this example, the Direction enum class has a property degrees and a method rotate. The rotate method is used to rotate the direction by a specified number of degrees.

Kotlin Program

enum class Direction(val degrees: Int) {
    NORTH(0), SOUTH(180), EAST(90), WEST(270);

    fun rotate(degrees: Int): Direction {
        val newDegrees = (this.degrees + degrees) % 360
        return values().first { it.degrees == newDegrees }
    }
}

fun main() {
    val currentDirection = Direction.NORTH
    println("Current direction: $currentDirection")

    val rotatedDirection = currentDirection.rotate(90)
    println("Rotated direction: $rotatedDirection")
}

Output

Current direction: NORTH
Rotated direction: EAST

Summary

Enum classes are a powerful feature in Kotlin, providing a clean and concise way to represent a set of related values.

They are often used in scenarios where you have a fixed set of options, such as representing days of the week, months, or various states in a finite state machine.