Kotlin Enum Classes - Defining Enumerations
Enum classes in Kotlin allow you to define a set of named values, making your code more readable and expressive when working with predefined constants. In this guide, we'll explore enum classes, how to define them, and their practical use cases.
Defining an Enum Class
You can define an enum class in Kotlin using the enum class
keyword. Here's an example:
enum class Color {
RED, GREEN, BLUE
}
The Color
enum class defines a set of named values representing colors.
Using Enum Values
You can use the values defined in an enum class like this:
val selectedColor = Color.RED
if (selectedColor == Color.RED) {
println("You selected the color red.")
}
Iterating Over Enum Values
You can iterate over the enum values using a for
loop:
for (color in Color.values()) {
println("Color: $color")
}
Custom Properties and Methods
You can add properties and methods to enum classes:
enum class Direction(val degrees: Int) {
NORTH(0),
EAST(90),
SOUTH(180),
WEST(270);
fun description(): String {
return "Moving $degrees degrees"
}
}
val currentDirection = Direction.NORTH
val description = currentDirection.description()
Companion Objects
Enum classes also have companion objects that allow you to define functions and properties related to the enum class:
enum class Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
companion object {
fun isWeekend(day: Day): Boolean {
return day == SATURDAY || day == SUNDAY
}
}
}
val today = Day.WEDNESDAY
val isWeekend = Day.isWeekend(today)
Conclusion
Enum classes in Kotlin provide a concise and expressive way to define a set of named constant values. Whether you're working with colors, directions, days of the week, or any other predefined constants, enum classes make your code more readable and maintainable.
Happy coding!