Welcome to our comprehensive guide on Kotlin Enum Classes! In this lesson, we'll dive deep into the world of enumerations in Kotlin. By the end of this tutorial, you'll have a solid understanding of how to use enum classes in your own projects. Let's get started!
In Kotlin, an enum (enumeration) is a special type of class that represents a set of named constants. Enum classes provide several advantages, such as type safety, convenience, and improved readability.
To create an enum class in Kotlin, simply define a class and use the enum keyword:
enum class Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}In this example, Day is our enum class, and we've defined seven possible values (or instances) of the enum.
You can access an enum value by its name:
val today = Day.FRIDAY
println("Today is $today") // Output: Today is FRIDAYYou can also iterate over all enum values using the values property:
for (day in Day.values) {
println("$day is a day of the week")
}You can add properties to your enum classes to associate data with each enumeration. Let's add a length property to our Day enum to represent the number of hours in each day:
enum class Day(val length: Int) {
MONDAY(24), TUESDAY(24), WEDNESDAY(24), THURSDAY(24), FRIDAY(24), SATURDAY(24), SUNDAY(24)
}Now you can access the length of each day using the length property:
val today = Day.FRIDAY
println("Today has ${today.length} hours.")You can also define methods in your enum classes to encapsulate related functionality. For example, let's create a method to determine if a day is a weekend:
enum class Day(val length: Int) {
MONDAY(24), TUESDAY(24), WEDNESDAY(24), THURSDAY(24), FRIDAY(24), SATURDAY(24), SUNDAY(24)
fun isWeekend() = this == SATURDAY || this == SUNDAY
}Now you can check if a day is a weekend using the isWeekend() method:
val today = Day.FRIDAY
println("${if (today.isWeekend()) "It's" else "It's not"} a weekend.")What is an Enum class in Kotlin?
That's it for our Kotlin Enum Classes tutorial! By now, you should have a solid understanding of how to create, access, and manipulate enum classes in your Kotlin projects. Happy coding! 🤖🚀