0
0
Kotlinprogramming~5 mins

When with ranges and types in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Ain
Bis
Crange
Dwithin
How do you check if a variable is of type String in a when expression?
Ais String
Bin String
Ctype String
Dequals String
What must you include in a when expression to handle all unmatched cases?
Acatch
Bdefault
Celse
Dfinally
What will this when expression print if value = 15? <br> when(value) { in 1..10 -> "Low"; in 11..20 -> "Medium"; else -> "High" }
ALow
BMedium
CHigh
DError
Can when be used without an argument in Kotlin?
ANo, it always needs an argument
BOnly with types
COnly with ranges
DYes, it can be used as an if-else chain
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.