Kotlin Enums: A Concise Guide

Kotlin Enums are a special type of class and it represents a fixed set of constants. Each constant in an Enum class is an instance of Enum class itself. Enums are useful when you have a predefined list of values that do not change, such as days of week, directions, states of a process etc.

Defining Kotlin Enums

It is very easy to define Enum in Kotlin. We use the enum keyword followed by the class name and a list of constants. These constants are represented in uppercase letters. Let’s see the example:

enum class Direction {
    NORTH, SOUTH, EAST, WEST
}

In the above example, Direction is an enum class with four constants NORTH, SOUTH, EAST, and WEST.

Accessing Kotlin Enums

It is very simple to access constants of an enum class. We use the enums class name followed by the constant name to access it. Let see through example:

enum class Direction {
    NORTH, SOUTH, EAST, WEST
}

fun main() {
    val direction = Direction.EAST
    println(direction)
}

// Output: EAST

Enum Properties and Methods

Enums in Kotlin can have properties and method, like other regular classes. Let’s see how can we define properties inside enum class and override functions:

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

    fun description(): String {
        return "Direction is $degrees degrees"
    }
}

fun main() {
    val direction = Direction.EAST
    println(direction.description())  
}

// Output: Direction is 90 degrees

In the above code:

  • We add a degrees property to each enum constant by defining it in primary constructor.
  • We define a method description() that provides a formatted string describing the direction in degrees.

See Also : A Beginner’s Guide To Kotlin Lambdas

Enum with Custom Methods

We can also add custom method to an enum class to handle specific logic related to the enum constants. For example, we want to get next direction in a clockwise direction:

enum class Direction {
    NORTH, EAST, SOUTH, WEST;

    fun next(): Direction {
        return when (this) {
            NORTH -> EAST
            EAST -> SOUTH
            SOUTH -> WEST
            WEST -> NORTH
        }
    }
}

fun main() {
    val direction = Direction.NORTH
    println(direction.next())  
}

// Output: EAST

The above written next() method written direction in clockwise order. Let’s say, if we call for SOUTH then it return WEST.

Enum Constants with Different Behaviors

Enum in Kotlin is much capable than any other language. We can use enum constants to exhibit different behaviors. In simple words, Kotlin enums allow to override methods for each constant. Let’s see how:

enum class Operation {
    ADD {
        override fun apply(x: Int, y: Int) = x + y
    },
    SUBTRACT {
        override fun apply(x: Int, y: Int) = x - y
    },
    MULTIPLY {
        override fun apply(x: Int, y: Int) = x * y
    },
    DIVIDE {
        override fun apply(x: Int, y: Int) = x / y
    };

    abstract fun apply(x: Int, y: Int): Int
}

fun main() {
    val operation1 = Operation.ADD
    val operation2 = Operation.DIVIDE
    println(operation1.apply(5, 3))  // Output: 8
    println(operation2.apply(10, 2)) // Output: 5
}

In the above code, we can clearly see that each constant of Operation Enum class override apply abstract function and provides it’s own implementation.

See Also : A Beginner’s Guide To Kotlin Lambdas

Kotlin Enums in Sealed Classes

I hope you are familiar with Kotlin’s Sealed Classes and if you are then you may know that Kotlin’s sealed classes and enums can be used together to achieve complex hierarchies. Let’s take an example of combining enums with sealed classes to represent different shapes:

sealed class Shape {
    data class Circle(val radius: Double) : Shape()
    data class Rectangle(val width: Double, val height: Double) : Shape()
    enum class TriangleType {
        EQUILATERAL, ISOSCELES, SCALENE
    }
    data class Triangle(val type: TriangleType, val base: Double, val height: Double) : Shape()
}

fun main() {
    val shape: Shape = Shape.Triangle(Shape.TriangleType.EQUILATERAL, 3.0, 4.0)
    when (shape) {
        is Shape.Circle -> println("Circle with radius ${shape.radius}")
        is Shape.Rectangle -> println("Rectangle with width ${shape.width} and height ${shape.height}")
        is Shape.Triangle -> println("Triangle of type ${shape.type} and with base ${shape.base} and height ${shape.height}")
    }
}

In the above example, we define a sealed class Shape with different subclasses to represent various shapes. The Triangle sub class uses an enum TriangleType to specify the type of triangle

Conclusion

Enums in Kotlin is a very powerful tool that can simiplify code by providing a clear and type-safe way to define a set of constants. It helps us write code error free. The above given examples cover a small part of enums and i hope you will explore it more yourself. I hope this blog post teaches you something and help you to write more expressive code with Kotlin Enums.

Happy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *