Challenge - 5 Problems
Enum Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of enum usage in Kotlin
What is the output of this Kotlin code that uses an enum to restrict values?
Kotlin
enum class Direction { NORTH, SOUTH, EAST, WEST } fun main() { val dir = Direction.NORTH println("Direction is: $dir") }
Attempts:
2 left
💡 Hint
Remember enums print their name exactly as declared.
✗ Incorrect
In Kotlin, enums print their name property by default, which is the exact uppercase string declared.
🧠 Conceptual
intermediate1:30remaining
Why enums restrict values
Why do enums in Kotlin constrain the possible values a variable can have?
Attempts:
2 left
💡 Hint
Think about how enums limit choices.
✗ Incorrect
Enums define a fixed set of named constants, so variables of enum type can only hold those values, preventing invalid assignments.
🔧 Debug
advanced2:00remaining
Identify the error with enum assignment
What error occurs when you try to assign a value not defined in the enum?
Kotlin
enum class Color { RED, GREEN, BLUE } fun main() { val c: Color = Color.YELLOW println(c) }
Attempts:
2 left
💡 Hint
Check if the enum contains the value YELLOW.
✗ Incorrect
Since YELLOW is not defined in the Color enum, the compiler cannot find it, causing an unresolved reference error.
❓ Predict Output
advanced1:30remaining
Output when using enum ordinal
What is the output of this Kotlin code using enum ordinal values?
Kotlin
enum class Size { SMALL, MEDIUM, LARGE } fun main() { val s = Size.MEDIUM println(s.ordinal) }
Attempts:
2 left
💡 Hint
Ordinal starts counting from zero.
✗ Incorrect
The ordinal property returns the position of the enum constant starting at 0, so MEDIUM is at index 1.
🚀 Application
expert2:30remaining
Using enums to validate input
Given this Kotlin enum and function, what will be the output when calling validateDirection("UP")?
Kotlin
enum class Direction { UP, DOWN, LEFT, RIGHT } fun validateDirection(input: String): String { return try { val dir = Direction.valueOf(input) "Valid direction: $dir" } catch (e: IllegalArgumentException) { "Invalid direction" } } fun main() { println(validateDirection("UP")) }
Attempts:
2 left
💡 Hint
Check if 'UP' is a valid enum constant.
✗ Incorrect
The string 'UP' matches an enum constant, so valueOf succeeds and returns that enum, producing the valid message.