An enum class in Kotlin is a type that represents a fixed set of constants or values. It is similar to an enum in other programming languages like Java. The values of an enum class are implicitly defined as constants so they can’t be changed, which makes them useful when you need to define a definitive set of options or states.
An enum class is defined using the ‘enum class‘ keyword followed by the class name and a set of constant values separated with commas. Here is an example of an enum class representing the days of the week:
enum class DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
You can use an enum class by accessing its values like you would access constants. For example, to print the value of the ‘MONDAY‘ constant in the ‘DayOfWeek‘ enum class, you can use:
println(DayOfWeek.MONDAY) // Output: MONDAY
An enum class can also have properties, methods and constructors like any other class. For example, you can define a property called ‘isWeekend‘ in the ‘DayOfWeek‘ enum class to check if a day is a weekend day:
enum class DayOfWeek(val isWeekend: Boolean) {
MONDAY(false), TUESDAY(false), WEDNESDAY(false),
THURSDAY(false), FRIDAY(false), SATURDAY(true), SUNDAY(true);
fun isWorkday() = !isWeekend
}
In this example, the ‘isWeekend‘ property is defined in the constructor of the ‘DayOfWeek‘ enum class. The ‘isWorkday‘ method is defined within the enum class and returns ‘true‘ if the day is not a weekend day.
You can then call the ‘isWeekend‘ and ‘isWorkday‘ methods of the ‘DayOfWeek‘ enum class on any of its values:
val saturday = DayOfWeek.SATURDAY
println(saturday.isWeekend) // Output: true
println(saturday.isWorkday()) // Output: false
In summary, an enum class is a type-safe way to define a fixed set of constants in Kotlin. They are useful in situations where you need to represent a limited set of options or states.