Skip to content

Adding Reverse Lookup to a Kotlin Enum

Kotlin, Enum, Android Development1 min read

Enums are a powerful construct in programming languages, including Kotlin. They allow us to define a set of constants in a more type-safe manner. However, there are times when we need to perform a reverse lookup, that is, finding an enum based on a certain property or value associated with it. In this article, we'll delve into the concept of reverse lookup in Kotlin enums and see how to implement it effectively. We'll explore its significance and provide examples to demonstrate its usage.

Understanding Kotlin Enums

In Kotlin, enums are used to define a collection of related constants. Each constant within the enum can have properties, methods, and even implement interfaces, making them quite versatile. Enums are especially useful when we want to define a specific, limited set of options for a certain variable.

Need for Reverse Lookup

While working with enums, there are instances where we might need to retrieve an enum based on a specific property or value associated with it. For example, consider a scenario where we want to obtain an enum based on a particular property it holds. This is where the concept of reverse lookup becomes valuable. By enabling reverse lookup, we can make our enums more adaptable and easier to work with in various situations.

Implementing Reverse Lookup

Let's dive into how we can add reverse lookup functionality to a Kotlin enum. We'll illustrate the process using a simple example.

1enum class Direction(val angle: Int) {
2 NORTH(0),
3 EAST(90),
4 SOUTH(180),
5 WEST(270);
7 companion object {
8 private val map = values().associateBy(Direction::angle)
9 fun fromAngle(angle: Int) = map[angle]
10 }
13fun main() {
14 val direction = Direction.fromAngle(90)
15 println("Direction for angle 90: ${direction?.name}")

In the above example, we have defined an enum called Direction, which represents cardinal directions along with their associated angles. By adding a companion object within the enum, we create a map that associates each angle with its corresponding direction. The fromAngle function then retrieves the direction based on the given angle. This way, we achieve reverse lookup for our enum. When we run the main function, we get the expected output as "EAST", showing that our reverse lookup implementation works as intended.

Enhancing Versatility

Adding reverse lookup to enums enhances their versatility and makes them more convenient to work with. It allows us to efficiently retrieve enum constants based on specific criteria, thus expanding their utility in various use cases. Whether it's mapping values, translating between different representations, or any other scenario where reverse lookup is required, this feature provides flexibility and ease of use.