Kotlin is a modern, statically typed language that provides several advanced features to facilitate software development. One of those features is the enumeration type, or enum, which is a special data type that enables for a variable to be a set of predefined constants. Today, we take a deeper dive into some of the advanced capabilities of Kotlin’s enum types, with a focus on methods and properties.
Basic Enum Declaration
Enums in Kotlin are straightforward to declare. Here's a simple example:
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
This declaration defines an enum named Direction with four constants.
Adding Properties to Enums
Enums in Kotlin can have properties, just like any other type of class. This can be particularly useful to associate specific information with each constant. Here is an example where each Direction has a string value:
enum class Direction(val degree: Int) {
NORTH(0), SOUTH(180), EAST(90), WEST(270);
}
In this example, each Direction constant is associated with an integer value representing degrees.
Enum Methods
Just as with other classes in Kotlin, enums can contain methods. This allows encapsulating behaviors directly with the related constants. Here’s an example demonstrating how to handle rotational operations with additional methods within the enum class:
enum class Direction {
NORTH, SOUTH, EAST, WEST;
fun turnRight(): Direction {
return when(this) {
NORTH -> EAST
EAST -> SOUTH
SOUTH -> WEST
WEST -> NORTH
}
}
fun turnLeft(): Direction {
return when(this) {
NORTH -> WEST
WEST -> SOUTH
SOUTH -> EAST
EAST -> NORTH
}
}
}
In this code, we define two methods: turnRight and turnLeft, which change the direction based on the current orientation.
Working with Companion Objects
Sometimes you might want to add some functionality that does not act on instance context but on the enum class itself. This is where the companion object comes in handy:
enum class Planet(val mass: Double, val radius: Double) {
EARTH(5.976e24, 6.378e6),
MARS(6.421e23, 3.397e6);
companion object {
fun fromMass(mass: Double) = values().firstOrNull { it.mass == mass }
}
}
By adding a companion object, we gain the ability to define methods that are callable on the enum class itself. In this example, fromMass retrieves a planet by its mass.
Iterating Through Enums
Finally, it is often required to loop over all constants of an enum. We can achieve this by using the values() function:
for (direction in Direction.values()) {
println(direction)
}
This function returns an array containing all constants of the enum in their declared order, allowing you to iterate over them easily.
Conclusion
Kotlin’s enums are not just static constants but powerful types enriched by properties and functions, safely encapsulating logic relevant to their state. By leveraging these advanced features, you can effectively utilize enum types within your applications to deliver clean and well-structured code.