September 2019
Intermediate to advanced
462 pages
11h 3m
English
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.
Here’s an excerpt of code where the suits properties are converted to use an enum class Suit instead of being a String:
| | 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 ... |
Read now
Unlock full access