Welcome to our comprehensive guide on Kotlin Enum Constants! In this tutorial, we'll explore what enum constants are, why they're important, and how to use them effectively in your projects. Let's dive right in!
In Kotlin, an enum (Enumeration) is a special class that represents a set of named constants. These constants are also known as enum constants or enum values. Enums can be used to represent a finite set of related values, such as the days of the week, colors, or HTTP status codes.
enum class Days {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}In the above example, Days is an enum class, and MONDAY, TUESDAY, and so on, are its enum constants.
Type Safety: Enum constants are strongly typed, which means that you can't accidentally assign the wrong value to an enum variable.
Immutability: Enum constants are immutable, meaning once they are created, they cannot be changed.
Readability: Enums make your code more readable as they provide self-documenting, meaningful names for a set of related constants.
Every enum constant is an instance of the enum class and has several built-in properties:
.ordinal: Returns the position of the enum constant in the enum declaration order. The first enum constant has an ordinal of 0.
.name: Returns the name of the enum constant as a string.
Here's an example:
enum class Planet {
MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE
}
println(Planet.EARTH.ordinal) // Output: 3 (because Earth is the 4th planet in the declaration)
println(Planet.EARTH.name) // Output: EARTHYou can also define custom properties and functions for your enum constants.
enum class Planet(val size: Double) {
MERCURY(0.38), VENUS(0.95), EARTH(1.0), MARS(0.54), JUPITER(11.2), SATURN(9.6), URANUS(4.0), NEPTUNE(3.9)
}
println(Planet.EARTH.size) // Output: 1.0 (the size of Earth)when Expression 💡The when expression is a powerful feature in Kotlin that allows you to match against multiple expressions, including enum constants. This can be used for polymorphism and more!
fun displayPlanet(planet: Planet) {
when (planet) {
Planet.MERCURY -> println("The smallest planet in our solar system.")
Planet.VENUS -> println("The second planet from the sun.")
Planet.EARTH -> println("Home sweet home!")
Planet.MARS -> println("The red planet.")
Planet.JUPITER -> println("The largest planet in our solar system.")
Planet.SATURN -> println("Known for its beautiful rings.")
Planet.URANUS -> println("The third largest planet.")
Planet.NEPTUNE -> println("The farthest planet from the sun.")
}
}
displayPlanet(Planet.EARTH) // Output: Home sweet home!What is an enum class in Kotlin?
That's it for our introductory lesson on Kotlin Enum Constants! We hope you enjoyed learning and found this tutorial helpful. In the next lesson, we'll delve deeper into enums and their capabilities. Stay tuned! 🎯