0
0
Kotlinprogramming~10 mins

Enum with when exhaustive check in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an enum class named Direction.

Kotlin
enum class [1] {
    NORTH, SOUTH, EAST, WEST
}
Drag options to blanks, or click blank then click option'
AMove
Bdirection
CDirections
DDirection
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase or plural names for enum class.
2fill in blank
medium

Complete the when expression to check the direction variable.

Kotlin
fun describeDirection(direction: Direction): String {
    return when ([1]) {
        Direction.NORTH -> "Going north"
        Direction.SOUTH -> "Going south"
        Direction.EAST -> "Going east"
        Direction.WEST -> "Going west"
    }
}
Drag options to blanks, or click blank then click option'
Adirection
Bdir
Cd
Dmove
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that does not exist in the function.
3fill in blank
hard

Fix the error by making the when expression exhaustive.

Kotlin
fun describeDirection(direction: Direction): String {
    return when (direction) {
        Direction.NORTH -> "North"
        Direction.SOUTH -> "South"
        Direction.EAST -> "East"
        [1] -> "West"
        // Missing WEST case causes error
    }
}
Drag options to blanks, or click blank then click option'
ADirection.WEST
BDirection.UP
CDirection.DOWN
DDirection.LEFT
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent enum values or missing cases.
4fill in blank
hard

Fill both blanks to create an exhaustive when expression without else.

Kotlin
fun describeDirection(direction: Direction): String {
    return when ([1]) {
        Direction.NORTH -> "North"
        Direction.SOUTH -> "South"
        Direction.EAST -> "East"
        [2] -> "West"
    }
}
Drag options to blanks, or click blank then click option'
Adirection
Bdir
CDirection.WEST
DDirection.UP
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names or missing enum cases.
5fill in blank
hard

Fill all three blanks to return a message using when with exhaustive check and smart casting.

Kotlin
sealed class Result {
    data class Success(val data: String): Result()
    object Failure: Result()
}

fun handleResult(result: Result): String {
    return when ([1]) {
        is Result.Success -> "Data: [2]"
        [3] -> "Failed"
    }
}
Drag options to blanks, or click blank then click option'
Aresult
Bresult.data
CResult.Failure
Dresult.failure
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names or missing the object case.