Creating and Using 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
:
Press + to interact
enum class Suit { CLUBS, DIAMONDS, HEARTS, SPADES }sealed class Card(val suit: Suit)class Ace(suit: Suit) : Card(suit)class King(suit: Suit) : Card(suit) {override fun toString() = "King of $suit"}//...
Likewise, instead of passing a String
to the constructor, we can now pass an instance of ...