Enum Classes in Kotlin

Learn about Enum classes in Kotlin and how to initialize the enums. Kotlin Example for Enum Class is provided for demonstration.

Enum Classes in Kotlin

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

Syntax :

Following is the syntax to define an Enum class in Kotlin

enum class <enum_class_name> {
    constant1, constant2, constant3

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” :


Kotlin Enums Initialization

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

Kotlin Enum


Kotlin Enum Example – To demonstrate the usage of Enum Classes

Following example demonstrates the usage of enum class MobileColor. Data Class, Mobile, has a variable as Enum class, MobileColor Object.


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 may do so for regular classes.


Conclusion :

In this Kotlin Tutorial, we have learnt about Enum Classes in Kotlin with a Kotlin Example to understand the usage.