0
0
Kotlinprogramming~20 mins

Why enums constrain values in Kotlin - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Enum Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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")
}
ADirection is: 0
BDirection is: North
CDirection is: NORTH
DCompilation error
Attempts:
2 left
💡 Hint
Remember enums print their name exactly as declared.
🧠 Conceptual
intermediate
1:30remaining
Why enums restrict values
Why do enums in Kotlin constrain the possible values a variable can have?
ABecause enums are mutable and can change values at runtime.
BBecause enums allow any string value to be assigned.
CBecause enums automatically convert values to integers.
DBecause enums define a fixed set of constants, preventing invalid values.
Attempts:
2 left
💡 Hint
Think about how enums limit choices.
🔧 Debug
advanced
2: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)
}
ACompilation error: Unresolved reference: YELLOW
BRuntime error: IllegalArgumentException
CPrints 'YELLOW' without error
DCompilation error: Type mismatch
Attempts:
2 left
💡 Hint
Check if the enum contains the value YELLOW.
Predict Output
advanced
1: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)
}
A1
B2
CCompilation error
D0
Attempts:
2 left
💡 Hint
Ordinal starts counting from zero.
🚀 Application
expert
2: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"))
}
AInvalid direction
BValid direction: UP
CCompilation error
DRuntime error: NullPointerException
Attempts:
2 left
💡 Hint
Check if 'UP' is a valid enum constant.