Enum classes in Kotlin are a powerful feature for representing a fixed set of constants. They combine the flexibility of classes with the type-safety of enumerations, making them a versatile tool for many programming scenarios.
To define an enum class in Kotlin, use the enum class
keywords followed by the class name and a list of constants:
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
Kotlin enum classes can have properties and methods, making them more powerful than traditional enumerations:
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF);
fun containsRed() = (rgb and 0xFF0000 != 0)
}
In this example, each constant has an associated RGB value, and we've defined a method to check if the color contains red.
Enum classes can be used in various contexts, such as Kotlin When Expressions or as function parameters:
fun chooseDirection(direction: Direction) = when(direction) {
Direction.NORTH -> "Going north"
Direction.SOUTH -> "Going south"
Direction.EAST -> "Going east"
Direction.WEST -> "Going west"
}
Enum classes in Kotlin can implement interfaces, allowing for even more flexibility:
interface Printable {
fun print(): String
}
enum class Status : Printable {
WAITING {
override fun print() = "Waiting..."
},
RUNNING {
override fun print() = "Running..."
},
FINISHED {
override fun print() = "Finished!"
}
}
Kotlin enum classes offer some advanced features that set them apart from traditional enumerations:
You can define anonymous classes for individual enum constants:
enum class Operation(val symbol: String) {
PLUS("+") {
override fun apply(x: Int, y: Int) = x + y
},
MINUS("-") {
override fun apply(x: Int, y: Int) = x - y
};
abstract fun apply(x: Int, y: Int): Int
}
Enum classes can have companion objects, allowing you to define shared functionality:
enum class Planet(val mass: Double, val radius: Double) {
EARTH(5.97e24, 6.37e6),
MARS(6.42e23, 3.39e6);
companion object {
fun findLargest(p1: Planet, p2: Planet): Planet {
return if (p1.mass > p2.mass) p1 else p2
}
}
}
By mastering enum classes, you can create more expressive and type-safe code in Kotlin. They provide a powerful way to represent fixed sets of constants with added functionality, making your code more robust and easier to maintain.