Kotlin Enum Class

Kotlin Enum – Enum is a special data type that allows a variable to hold a value only from a set of predefined constants.

In this tutorial, we shall learn about Kotlin Enum Class : Syntax, Initialization, how enum classes are different from regular classes. An example program is provided to demonstrate the usage of Kotlin Enum.

Syntax

Following is the syntax to define an Enum class in Kotlin

Any number of constants could be specified inside the class separated by comma. Each Enum constant is implicitly an Object of type <enum_class_name>.

Following is an example of defining a Kotlin Enum class “MobileColor” with constants GOLD, SILVER, WHITE, BLACK and RED.

Kotlin Enum Initialization

As Kotlin Enum is an object of an Enum class, these enum objects could be initialized. We shall use the same example of MobileColor enum class to demonstrate the initialization of enums.

Kotlin Enum

Please note that we have provided val in the definition, since the value has to be a constant.

Example – Kotlin Enum Class

Following Kotlin Application demonstrates the usage of enum class MobileColor.

We have initialized a Data Class, Mobile, which has a value named color that can accept an Enum object of Enum class type MobileColor.

Now let us try the same example, without having any value for the Enum constants.

We have not given any value initialized for Enum constants.

Now, run this application and you shall see the following output in Console.

How enum class is different from a regular class

You cannot create new instances of an Enum class outside of its definition. In other words outside enum definition, you cannot create an object of type Enum Class by passing values to its primary constructor. You can do so for regular classes.

Conclusion

In this Kotlin TutorialKotlin Enum Classes, we have learnt the syntax and usage with help of an Example program.