0
0
Kotlinprogramming~20 mins

Enum entries iteration in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Enum Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of iterating enum entries with for loop
What is the output of this Kotlin code that iterates over enum entries using a for loop?
Kotlin
enum class Color { RED, GREEN, BLUE }

fun main() {
    for (color in Color.values()) {
        println(color)
    }
}
Ared\ngreen\nblue
BRED\nGREEN\nBLUE
CColor.RED\nColor.GREEN\nColor.BLUE
DRED GREEN BLUE
Attempts:
2 left
💡 Hint
Remember that printing enum entries calls their toString() method which returns the name by default.
Predict Output
intermediate
2:00remaining
Output of iterating enum entries with forEach and lambda
What will this Kotlin code print when iterating enum entries with forEach and a lambda?
Kotlin
enum class Direction { NORTH, EAST, SOUTH, WEST }

fun main() {
    Direction.values().forEach { println(it.name.lowercase()) }
}
Anorth\neast\nsouth\nwest
BNORTH\nEAST\nSOUTH\nWEST
CDirection.NORTH\nDirection.EAST\nDirection.SOUTH\nDirection.WEST
Dnorth east south west
Attempts:
2 left
💡 Hint
The name property returns the enum constant name as declared. The lowercase() function converts it to lowercase.
🧠 Conceptual
advanced
2:00remaining
Understanding enum entries iteration with indices
Given this Kotlin code, what is the output when iterating enum entries with their indices?
Kotlin
enum class Level { LOW, MEDIUM, HIGH }

fun main() {
    Level.values().forEachIndexed { index, level ->
        println("$index: $level")
    }
}
ALevel.LOW: 0\nLevel.MEDIUM: 1\nLevel.HIGH: 2
BLOW: 0\nMEDIUM: 1\nHIGH: 2
C0 LOW\n1 MEDIUM\n2 HIGH
D0: LOW\n1: MEDIUM\n2: HIGH
Attempts:
2 left
💡 Hint
forEachIndexed provides the index and the element in order.
🔧 Debug
advanced
2:00remaining
Identify the error in enum iteration code
What error does this Kotlin code produce when trying to iterate enum entries?
Kotlin
enum class Status { STARTED, RUNNING, FINISHED }

fun main() {
    for (s in Status) {
        println(s)
    }
}
ANo error, prints STARTED RUNNING FINISHED
BError: Missing parentheses after Status
CError: 'Status' is not iterable
DError: Cannot use enum class in for loop
Attempts:
2 left
💡 Hint
You must call values() to get an array of enum entries to iterate.
🚀 Application
expert
2:00remaining
Count enum entries with a specific property
Given this enum with a property, what is the output of counting entries with isActive = true?
Kotlin
enum class TaskStatus(val isActive: Boolean) {
    TODO(true), IN_PROGRESS(true), DONE(false), CANCELLED(false)
}

fun main() {
    val activeCount = TaskStatus.values().count { it.isActive }
    println(activeCount)
}
A2
B4
C3
D1
Attempts:
2 left
💡 Hint
Check which enum entries have isActive set to true.