Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to return a string in else branch.
Using a number instead of a string in else.
✗ Incorrect
The else branch must return a string value. "Other" is the correct default string here.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning "Odd" for even numbers.
Using numbers instead of strings as return values.
✗ Incorrect
The first condition checks if number is even, so it should return "Even".
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning input directly which is an Int, causing type mismatch.
Returning input.length which is invalid for Int.
✗ Incorrect
The when expression must return a string. "Number" is the correct string for Int input.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using input.length instead of value.length inside when.
Returning null instead of 0 for else case.
✗ Incorrect
For a String input, return its length. Otherwise, return 0.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the threshold values.
Returning a number instead of a string in else.
✗ Incorrect
Scores 90 or above get "Excellent", 60 or above get "Good", else "Try again".