Sling Academy
Home/Kotlin/Advanced Enum Features in Kotlin: Methods and Properties

Advanced Enum Features in Kotlin: Methods and Properties

Last updated: December 05, 2024

Kotlin is a modern, statically typed language that provides several advanced features to facilitate software development. One of those features is the enumeration type, or enum, which is a special data type that enables for a variable to be a set of predefined constants. Today, we take a deeper dive into some of the advanced capabilities of Kotlin’s enum types, with a focus on methods and properties.

Basic Enum Declaration

Enums in Kotlin are straightforward to declare. Here's a simple example:


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

This declaration defines an enum named Direction with four constants.

Adding Properties to Enums

Enums in Kotlin can have properties, just like any other type of class. This can be particularly useful to associate specific information with each constant. Here is an example where each Direction has a string value:


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

In this example, each Direction constant is associated with an integer value representing degrees.

Enum Methods

Just as with other classes in Kotlin, enums can contain methods. This allows encapsulating behaviors directly with the related constants. Here’s an example demonstrating how to handle rotational operations with additional methods within the enum class:


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

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

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

In this code, we define two methods: turnRight and turnLeft, which change the direction based on the current orientation.

Working with Companion Objects

Sometimes you might want to add some functionality that does not act on instance context but on the enum class itself. This is where the companion object comes in handy:


enum class Planet(val mass: Double, val radius: Double) {
    EARTH(5.976e24, 6.378e6),
    MARS(6.421e23, 3.397e6);

    companion object {
        fun fromMass(mass: Double) = values().firstOrNull { it.mass == mass }
    }
}

By adding a companion object, we gain the ability to define methods that are callable on the enum class itself. In this example, fromMass retrieves a planet by its mass.

Iterating Through Enums

Finally, it is often required to loop over all constants of an enum. We can achieve this by using the values() function:


for (direction in Direction.values()) {
    println(direction)
}

This function returns an array containing all constants of the enum in their declared order, allowing you to iterate over them easily.

Conclusion

Kotlin’s enums are not just static constants but powerful types enriched by properties and functions, safely encapsulating logic relevant to their state. By leveraging these advanced features, you can effectively utilize enum types within your applications to deliver clean and well-structured code.

Next Article: Best Practices for Writing Object-Oriented Code in Kotlin

Previous Article: Defining and Using Enum Classes in Kotlin

Series: Kotlin Object-Oriented Programming

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin