Recall & Review
beginner
What is the
when expression in Kotlin used for?The
when expression in Kotlin is used as a replacement for the switch statement in other languages. It allows you to check a value against multiple conditions, including ranges and types, and execute code based on the matching case.Click to reveal answer
beginner
How do you check if a value is within a range using
when in Kotlin?You use the
in keyword inside a when branch to check if a value falls within a range. For example: in 1..10 checks if the value is between 1 and 10 inclusive.Click to reveal answer
beginner
How can you check the type of a variable in a
when expression?You can use the
is keyword in a when branch to check if a variable is of a certain type. For example: is String checks if the variable is a String.Click to reveal answer
intermediate
What happens if none of the
when branches match a value?If none of the branches match, and there is no
else branch, the when expression will throw a NoWhenBranchMatchedException. To avoid this, always include an else branch as a fallback.Click to reveal answer
beginner
Write a simple Kotlin
when expression that prints "Small" if a number is between 1 and 10, "Medium" if between 11 and 100, and "Large" otherwise.```kotlin
val number = 25
when (number) {
in 1..10 -> println("Small")
in 11..100 -> println("Medium")
else -> println("Large")
}
```
Click to reveal answer
Which keyword is used in Kotlin's
when expression to check if a value is within a range?✗ Incorrect
The keyword
in is used to check if a value falls inside a range, like in 1..10.How do you check if a variable is of type String in a
when expression?✗ Incorrect
The
is keyword checks the type of a variable, for example is String.What must you include in a
when expression to handle all unmatched cases?✗ Incorrect
The
else branch acts as a fallback for any unmatched cases in a when expression.What will this
when expression print if value = 15? <br> when(value) { in 1..10 -> "Low"; in 11..20 -> "Medium"; else -> "High" }✗ Incorrect
Since 15 is in the range 11 to 20, the expression returns "Medium".
Can
when be used without an argument in Kotlin?✗ Incorrect
When used without an argument,
when acts like an if-else chain checking conditions.Explain how to use the
when expression in Kotlin to check if a number falls within certain ranges.Think about how you check if a number is between two values.
You got /5 concepts.
Describe how to use
when to check the type of a variable and why this might be useful.Consider how Kotlin can automatically treat a variable as a specific type after checking.
You got /5 concepts.