Challenge - 5 Problems
Enum Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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) } }
Attempts:
2 left
💡 Hint
Remember that printing enum entries calls their toString() method which returns the name by default.
✗ Incorrect
The values() function returns all enum entries. Printing each entry prints its name in uppercase as declared.
❓ Predict Output
intermediate2: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()) } }
Attempts:
2 left
💡 Hint
The name property returns the enum constant name as declared. The lowercase() function converts it to lowercase.
✗ Incorrect
Each enum entry's name is converted to lowercase and printed on its own line.
🧠 Conceptual
advanced2: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") } }
Attempts:
2 left
💡 Hint
forEachIndexed provides the index and the element in order.
✗ Incorrect
The index starts at 0 and increments by 1 for each enum entry. The output prints index and enum name separated by colon.
🔧 Debug
advanced2: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) } }
Attempts:
2 left
💡 Hint
You must call values() to get an array of enum entries to iterate.
✗ Incorrect
Enum classes are not directly iterable. You must use Status.values() to get the array of entries.
🚀 Application
expert2: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) }
Attempts:
2 left
💡 Hint
Check which enum entries have isActive set to true.
✗ Incorrect
TODO and IN_PROGRESS have isActive = true, so count is 2.