Kotlin Enum Classes 🎯

beginner
20 min

Kotlin Enum Classes 🎯

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!

What are Enum Classes? 📝

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.

Why use Enum Classes? 💡

  1. Type safety: Enum classes ensure that a variable can only hold values from a specific, predefined set. This helps prevent errors caused by incorrect data types.
  2. Convenience: Enum classes make it easier to manage a group of related constants. You can add properties and methods to each enumeration to encapsulate related functionality.
  3. Improved readability: By grouping related constants and associated functionality together, enum classes make your code easier to understand and maintain.

Declaring an Enum Class 🎯

To create an enum class in Kotlin, simply define a class and use the enum keyword:

kotlin
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.

Accessing Enum Values 💡

You can access an enum value by its name:

kotlin
val today = Day.FRIDAY println("Today is $today") // Output: Today is FRIDAY

You can also iterate over all enum values using the values property:

kotlin
for (day in Day.values) { println("$day is a day of the week") }

Enum Class Properties 💡

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:

kotlin
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:

kotlin
val today = Day.FRIDAY println("Today has ${today.length} hours.")

Enum Class Methods 💡

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:

kotlin
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:

kotlin
val today = Day.FRIDAY println("${if (today.isWeekend()) "It's" else "It's not"} a weekend.")

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🤖🚀