Enums Workbook


Practice problems for Enums in Kotlin. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.

the basics

1. A simple enum

Declare enum class Suit with HEARTS, DIAMONDS, CLUBS, SPADES.

Show answer Hide answer
enum class Suit { HEARTS, DIAMONDS, CLUBS, SPADES }

2. Exhaustive when

Write isRed(suit: Suit): Boolean returning true for HEARTS and DIAMONDS, using a when with no else.

Show answer Hide answer
fun isRed(suit: Suit) = when (suit) {
    Suit.HEARTS, Suit.DIAMONDS -> true
    Suit.CLUBS, Suit.SPADES -> false
}

data and behavior

3. Constructor properties

Declare enum class Planet(val gravity: Double) with EARTH(9.8) and MARS(3.7).

Show answer Hide answer
enum class Planet(val gravity: Double) {
    EARTH(9.8),
    MARS(3.7)
}

4. A method on the enum

Add a weightOf(mass: Double) method to Planet returning mass * gravity.

Show answer Hide answer
enum class Planet(val gravity: Double) {
    EARTH(9.8),
    MARS(3.7);

    fun weightOf(mass: Double) = mass * gravity
}

Note the ; after the last constant when members follow.

5. Per-constant behavior

Declare enum class Op with ADD and MULTIPLY, each overriding an abstract apply(a: Int, b: Int): Int.

Show answer Hide answer
enum class Op {
    ADD { override fun apply(a: Int, b: Int) = a + b },
    MULTIPLY { override fun apply(a: Int, b: Int) = a * b };

    abstract fun apply(a: Int, b: Int): Int
}

built-in members

6. Iterate the values

Given Suit, print every constant. Use the built-in that lists them.

Show answer Hide answer
for (s in Suit.entries) println(s)

(Suit.values() also works; entries is the newer, preferred form.)

7. Parse from a name

Turn the string "CLUBS" into the Suit.CLUBS constant.

Show answer Hide answer
Suit.valueOf("CLUBS")

8. Name and position

Given val s = Suit.SPADES, get its name as a string and its zero-based position.

Show answer Hide answer
s.name      // "SPADES"
s.ordinal   // 3

interfaces

9. An enum implementing an interface

Given interface Describable { fun describe(): String }, declare enum class Level : Describable with LOW and HIGH, each describing itself.

Show answer Hide answer
interface Describable { fun describe(): String }

enum class Level : Describable {
    LOW { override fun describe() = "low" },
    HIGH { override fun describe() = "high" }
}

10. A shared property

Declare enum class HttpStatus(val code: Int) with OK(200) and NOT_FOUND(404), and look up HttpStatus.OK.code.

Show answer Hide answer
enum class HttpStatus(val code: Int) {
    OK(200),
    NOT_FOUND(404)
}

HttpStatus.OK.code   // 200

Back to the lesson, Enums in Kotlin, or on to the next one: interfaces.

Comments