enum in Kotlin

Like to share

1. Overview

In this article, we will discuss the enum in Kotlin.

2. Enum classes

An Enum is a class that represents a group of constants. You can always use enums when a variable can only accept value out of a small set of known values. Examples would be things like type constants (directions: NORTH, SOUTH, EAST, WEST), or flags (Started, Paused, In progress, Completed).

The most basic use case for enum classes is the implementation of type-safe enums. It increases compile-time checking and avoid errors from passing in invalid constants. You can also document which values are valid to use and what it implies.

The enum constants are separated by commas and each of them is an object.

In the below example, enum constants GOLD, SILVER, BRONZE are all objects separated by commas.

enum class OlympicMedal {
   GOLD, SILVER, BRONZE
}

Since each enum is an instance of the enum class, it can be initialized as:

enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}
    val color = Color.RED
    if (color is Enum<*>) {
        println(true) 
    }

2.1. enum in Kotlin example

Let’s take an enum example. Suppose you want to track the user’s movement and the direction they are heading towards. For this, you had to create a function that should process the user’s direction and it should accept only the geographical directions as input. We already know the directions NORTH, SOUTH, EAST, WEST. So let’s create an enum Direction with those constant values.

Let’s the function be named getUserDirection which accepts only enum of type Direction. You can only pass enum constants as value to this function.

enum class Direction {
    NORTH, SOUTH, WEST, EAST
}
fun getUserDirection(direction : Direction) {
    println(direction.name)
}
fun main() {
    getUserDirection(Direction.NORTH)
}

If you pass anything else, then compiler would throw warning.

fun main() {
    getUserDirection("northern")
}

The above code will throw compilation warning “Type mismatch: inferred type is String but Direction was expected”

3. Enum Anonymous classes

Enum constants can declare their own anonymous classes with their corresponding methods. It can also override the base methods.

In the below example, Enum class defines an abstract base method getAmount and each enum constant has overridden that method. You should separate the enum constants from the members using the semicolon. Note that we have a semicolon between the base method and the enum constants.

enum class SalaryAmount {
    WITH_HIKE {
        override fun getAmount(currentSalary: Long) : Long {
            return currentSalary + 10000
        }
    },
    WITHOUT_HIKE {
        override fun getAmount(currentSalary: Long) : Long {
            return currentSalary
        }
    };
    abstract fun getAmount(currentSalary: Long): Long
}
fun main() {
    println(SalaryAmount.WITH_HIKE.getAmount(50000))
}

Result:

60000

4. Implementing interfaces in enum classes

An enum class can implement an interface providing either a common implementation of interface members for all the enum constants, or separate implementations for each constant within its anonymous class. Note that enum class can’t extend class. It can implement one or more interfaces.

Let’s take the same Salary example which we have seen in previous section.

Here, Enum class SalaryAmount implements the interface Amount with two abstract functions getAmount and getName. Each enum constant implements the getAmount method separately within its anonymous class whereas enum class provides a common implementation of getName that applies to all the enum constants.

interface Amount {
    fun getAmount(currentSalary: Long): Long
    fun getName() : String
}
enum class SalaryAmount : Amount {
    WITH_HIKE {
        override fun getAmount(currentSalary: Long) : Long {
            return currentSalary + 10000
        }
    },
    WITHOUT_HIKE {
        override fun getAmount(currentSalary: Long) : Long {
            return currentSalary
        }
    };
    override fun getName() : String {
        return "TedBlob"
    }
}
fun main() {
    println(SalaryAmount.WITH_HIKE.getAmount(50000))
    println(SalaryAmount.WITH_HIKE.getName())
}

Result:

60000

TedBlob

5. enum valueof kotlin

To get an enum constant by its name, you can use the function valueOf() on the Enum class. The return type of this function would be enum constant. By passing the string, you can get an enum constant which you can use later to call functions or any other operations.

The valueOf() method throws an IllegalArgumentException if the specified enum type has no constant with the specified name.

The signature of this method is:

<EnumClassName>.valueOf(value: String): <EnumClassName>

In the below example, you are passing the string “RED” to the method valueOf. It returns the enum constant object as “RED” exists in the Enum class. Later, you pass that object to getBugState method to know the bug state.

enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}
val color : Color = Color.valueOf("RED")
println(getBugState(color))
fun getBugState(color: Color) {
}

Result:

RED

6. Conclusion

In this article, we learned about the enum class in Kotlin.

If you like to learn more of Kotlin topics, please refer our Kotlin articles.

Leave a Reply

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