Enum Classes in Kotlin : Play with distinct values
In this Kotlin tutorial, we will explore the power and flexibility of enum classes in Kotlin and how they can contribute to writing cleaner and more reliable code.
Understanding Enums
Before we dive into enum classes in Kotlin, let’s briefly revisit the concept of enums in general. An enum, short for enumeration, is a special data type that consists of a fixed set of named values, often referred to as constants. These constants represent a unique and predefined set of options, and each option is typically associated with an underlying integer value or ordinal.
Enum classes serve as a powerful tool to represent types that encapsulate a finite and distinct collection of values, encompassing concepts like directions, states, modes, and more.
Declaring Enum Classes in Kotlin
In Kotlin, creating an enum class is as simple as using the enum keyword followed by the class name and curly braces:
enum class Play{
START, PAUSE, STOP
}
How to access enum ?
val play = Play.START
Kotlin enum Class example
Enum classes are often used in conjunction with Kotlin’s powerful when expression. The when
expression is similar to a switch statement in other programming languages but offers more flexibility and expressiveness.
fun main()
{
val play = Play.START
val message = when(play)
{
Play.START -> "Music started"
Play.PAUSE -> "Music paused"
Play.STOP -> "Music stopped"
}
println(message)
}
enum class Play{
START, PAUSE, STOP
}
Output
Music started
Properties and Methods in Enum Classes
One of the reasons enum classes in Kotlin are so powerful is their ability to have properties and methods associated with each constant.
package enum
enum class Direction(val degrees: Int) {
NORTH(0),
SOUTH(160),
EAST(80),
WEST(170);
fun getOpposite(): Direction {
return when (this) {
NORTH -> SOUTH
SOUTH -> NORTH
EAST -> WEST
WEST -> EAST
}
}
}
fun main()
{
val currentDirection = Direction.WEST
println("Current direction $currentDirection")
val oppositeDirection = currentDirection.getOpposite()
println("Opposite direction: $oppositeDirection")
}
Output
Current direction WEST
Opposite direction: EAST
In this example, we have added a property degrees to the Direction enum class. Additionally, we have a method getOpposite() that returns the opposite direction for a given direction. This flexibility enables code that is not only more readable but also more self-contained and less error-prone.
Using enum classes in Kotlin is intuitive. As with traditional enums, you can access enum constants by their names:
val currentDirection = Direction.WEST
println("Current direction $currentDirection")
You can also utilize the properties and methods associated with each constant:
val oppositeDirection = currentDirection.getOpposite()
println("Opposite direction: $oppositeDirection")
Happy coding!