Working with Enums in Kotlin

1. Overview

In this tutorial, we’ll deep dive into Kotlin enums.

With the evolution of programming languages, the usage and application of enums have also advanced.

Enum constants today aren’t just mere collections of constants – they can have properties, implement interfaces, and much more.

For Kotlin beginners, check out this article on Kotlin basics – Introduction to the Kotlin Language.

2. Basic Kotlin Enums

Let’s look at the basics of enums in Kotlin.

2.1. Defining Enums

Let’s define an enum as having three constants describing credit card types:

enum class CardType {
    SILVER, GOLD, PLATINUM
}

2.2. Initializing Enum Constants

Enums in Kotlin, just like in Java, can have a constructor. Since enum constants are instances of an Enum class, the constants can be initialized by passing specific values to the constructor.

Let’s specify color values to various card types:

enum class CardType(val color: String) {
    SILVER("gray"),
    GOLD("yellow"),
    PLATINUM("black")
}

We can access the color value of a specific card type with:

val color = CardType.SILVER.color

3. Enum Constants as Anonymous Classes

We can define specific enum constant behavior by creating them as anonymous classes. Constants then need to override the abstract functions defined within the Enum definition.

For example, for each card type, we may have different cash-back calculation.

Let’s see how we can implement it:

enum class CardType {
    SILVER {
        override fun calculateCashbackPercent() = 0.25f
    },
    GOLD {
        override fun calculateCashbackPercent() = 0.5f
    },
    PLATINUM {
        override fun calculateCashbackPercent() = 0.75f
    };

    abstract fun calculateCashbackPercent(): Float
}

We can invoke the overridden methods of the anonymous constant classes with:

val cashbackPercent = CardType.SILVER.calculateCashbackPercent()

4. Enums Implementing Interfaces

Let’s say there’s an ICardLimit interface which defines the card limits of various card types:

interface ICardLimit {
    fun getCreditLimit(): Int
}

Now, let’s see how our enum can implement this interface:

enum class CardType : ICardLimit {
    SILVER {
        override fun getCreditLimit() = 100000
    },
    GOLD {
        override fun getCreditLimit() = 200000
    },
    PLATINUM {
        override fun getCreditLimit() = 300000
    }
}

To access the credit limit of a card type, we can use the same approach as in the previous example:

val creditLimit = CardType.PLATINUM.getCreditLimit()

5. Common Enum Constructs


==== 5.1. Getting Enum Constants by Name

To get an enum constant by its String name, we use the valueOf() static function:

val cardType = CardType.valueOf(name.toUpperCase())

5.2. Iterating Through Enum Constants

To iterate through all enum constants, we use the values() static function:

for (cardType in CardType.values()) {
    println(cardType.color)
}

5.3. Static Methods

To add a “static” function to an enum, we can use a companion object:

companion object {
    fun getCardTypeByName(name: String) = valueOf(name.toUpperCase())
}

We can now invoke this function with:

val cardType = CardType.getCardTypeByName("SILVER")

Note that Kotlin doesn’t have a concept of static methods. What we’ve shown here a way to get the same functionality as in Java, but using Kotlin’s features.

6. Conclusion

This article makes an introduction to enums in Kotlin language and it’s key features.

We’ve introduced some simple concepts like defining enums and initializing the constants. We’ve also shown some advanced features like defining enum constants as anonymous classes, and enums implementing interfaces.

The implementation of all these examples and code snippets can be found in the GitHub project. This is a Maven project, so it should be easy to import and run as it is.

Leave a Reply

Your email address will not be published.