0
0
Kotlinprogramming~10 mins

When as expression returning value 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 assign the correct string based on the number using when expression.

Kotlin
val result = when (number) {
    1 -> "One"
    2 -> "Two"
    else -> [1]
}
Drag options to blanks, or click blank then click option'
A"Other"
B"Unknown"
C"Zero"
D"None"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to return a string in else branch.
Using a number instead of a string in else.
2fill in blank
medium

Complete the when expression to return "Even" for even numbers and "Odd" for odd numbers.

Kotlin
val parity = when {
    number % 2 == 0 -> [1]
    else -> "Odd"
}
Drag options to blanks, or click blank then click option'
A"Odd"
B"Zero"
C"Even"
D"None"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning "Odd" for even numbers.
Using numbers instead of strings as return values.
3fill in blank
hard

Fix the error in the when expression to correctly return a string for the input.

Kotlin
val description = when (input) {
    is String -> "Text"
    is Int -> [1]
    else -> "Unknown"
}
Drag options to blanks, or click blank then click option'
Ainput.toString()
Binput.length
Cinput
D"Number"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning input directly which is an Int, causing type mismatch.
Returning input.length which is invalid for Int.
4fill in blank
hard

Fill both blanks to create a when expression that returns the length of a string or zero otherwise.

Kotlin
val length = when (val value = input) {
    is String -> [1]
    else -> [2]
}
Drag options to blanks, or click blank then click option'
Avalue.length
B0
Cinput.length
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using input.length instead of value.length inside when.
Returning null instead of 0 for else case.
5fill in blank
hard

Fill all three blanks to create a when expression that returns a message based on the score value.

Kotlin
val message = when {
    score >= [1] -> "Excellent"
    score >= [2] -> "Good"
    else -> [3]
}
Drag options to blanks, or click blank then click option'
A90
B60
C"Try again"
D"Average"
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the threshold values.
Returning a number instead of a string in else.