Kotlin Enum Properties Tutorial 🎯

beginner
22 min

Kotlin Enum Properties Tutorial 🎯

Welcome back to CodeYourCraft! Today, we're diving into the world of Kotlin and exploring Enum Properties. These are powerful tools in our programming toolkit that help us write cleaner, more efficient code. Let's get started!

What are Enum Properties? 📝

Enum Properties are special properties that are defined within an enum class. They offer a concise and organized way to store values that are related to the enum constants.

kotlin
enum class Weekdays { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

In the above example, Weekdays is an enum class with seven constants. Each constant represents a day of the week.

Creating Enum Properties 💡

To create an Enum Property, simply add a val or var keyword before the property name inside the enum class.

kotlin
enum class Weekdays { MONDAY { val dayNumber = 1 }, TUESDAY { val dayNumber = 2 }, // ... }

In the example above, each constant now has an associated dayNumber property.

Accessing Enum Properties 💡

You can access an Enum Property by using the dot (.) notation with the enum constant.

kotlin
fun main() { println(Weekdays.MONDAY.dayNumber) // Prints: 1 }

Initializer Blocks for Enum Properties 💡

If you need to initialize Enum Properties with complex values, you can use initializer blocks.

kotlin
enum class Weekdays { MONDAY { val dayNumber = calculateDayNumber(this) }, TUESDAY { val dayNumber = calculateDayNumber(this) }, // ... private fun calculateDayNumber(day: Weekdays) = when (day) { Weekdays.MONDAY -> 1 Weekdays.TUESDAY -> 2 // ... } }

In the example above, the calculateDayNumber function is an initializer block that calculates the dayNumber for each constant.

Enum Properties vs Class Properties 💡

While enum properties may seem similar to class properties, there are some key differences. Enum properties are automatically initialized and cannot be changed once set. This helps prevent errors and makes the code more robust.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which keyword is used to define an Enum Property?

That's all for today! By now, you should have a good understanding of Kotlin Enum Properties. In the next lesson, we'll explore more advanced usage and real-world examples. Keep coding! 🤖🚀