Creating and Using Enums
Explore how to create and use enum classes in Kotlin to represent fixed sets of values like suits in cards. Learn to customize enums with properties and methods, iterate over their instances, and understand type safety benefits. This lesson helps you write cleaner and maintainable code by replacing arbitrary strings with enums.
We'll cover the following...
In the previous example, we used String to represent a suit, but that’s smelly. We don’t need arbitrary values for suit. We may create a sealed class Suit and derived classes for each of the four permissible types. In fact, there can be only four values for suit. In short, we don’t need classes, we simply need four instances. The enum class solves that problem elegantly.
Using enums
Here’s an excerpt of code where the suits properties are converted to use an enum class Suit instead of being a String:
Likewise, instead of passing a String to the constructor, we can now pass an instance of the enum class Suit:
// UseCardWithEnum.kt
println(process(Ace(Suit.DIAMONDS))) // Ace of DIAMONDS
println(process(Queen(Suit.CLUB ...