Enum classes in Kotlin Tutorial

In this tutorial we will learn about Enums in kotlin language.

we will learn how to declare Enum class and how to initialize Enum classes in Kotlin.

Enum in Kotlin is a custom data type that can contains set of constants.

In the Kotlin programming language we define an Enum using keyword “enum”.

Common examples of Enum include days of week, compass directions (North, East, West, South).

Anytime you need fixed set of constants you can use Enums in Kotlin.

This is how we define Enum class in Kotlin

enum class ColorEnum {
     Red, Green, Blue, Orange 
 }

we can define any number of constans in an Enum class in Kotlin.

Constants declared inside Enum class are object of Colors class.

How to initialize Enum class in Kotlin

As each constant inside class is object of Enum class.

We can initialize class instances like below.

enum class ColorEnum(val colorCode: Int) {
     Red(2),
     Blue(11212),
     Green(21212),    Orange(212121)
 } 

In above code snippet we have assigned value to each instance of enum class. 

How to iterate Enum class in Kotlin using for loop example

Above Enum class can be traversed using this code snippet

for (enum in ColorEnum.values()) {
     println(enum.colorCode)
 }

values() method in Enum class in kotlin the compiler adds values method internally.

And it returns an array of all the enum values.

Properties of Enum class

Each Enum Object has its own properties.

println(ColorEnum.valueOf("Orange").colorCode)

For example above code snippet will print color code for Orange object in Enum class.

Get index of Enum Object using ordinal property in Enum class in Kotlin

println(ColorEnum.valueOf("Orange").ordinal)

Above code snippet will print 3 as index of Orange, index always start from zero.

Using “when” to deal with Enum classes

we can apply “when” on Enum clasess, “when” in Kotlin is used as alternate of “switch” statement in Java.

var color = ColorEnum.Green
 
 when (color) {
     
     ColorEnum.Green -> {
         println("I am Green Color")
     }
     ColorEnum.Blue -> {
         println("I am Blue Color")
     }
     ColorEnum.Orange -> {
         println("I am Orange Color")
     }
     ColorEnum.Red -> {
         println("I am Red Color")
     }
     
 }

This is how “when” statement in Kotlin can be used with enums.

1 thought on “Enum classes in Kotlin Tutorial”

Leave a Reply

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