0
0
Kotlinprogramming~5 mins

When without argument in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a when expression without an argument in Kotlin?
A when without an argument works like an if-else if chain. Each branch checks a condition that returns a Boolean.
Click to reveal answer
beginner
How do you write a when expression without an argument?
You write when { condition1 -> action1; condition2 -> action2; else -> defaultAction }. Each condition is a Boolean expression.
Click to reveal answer
intermediate
What happens if none of the conditions in a when without argument match and there is no else branch?
The program throws a kotlin.NoWhenBranchMatchedException at runtime because no branch was matched.
Click to reveal answer
beginner
Can when without argument replace multiple if-else if statements?
Yes, it can make code cleaner and easier to read by grouping conditions in one expression.
Click to reveal answer
beginner
Example: What does this code print?<br>
when {
  5 > 10 -> println("Greater")
  5 < 10 -> println("Smaller")
  else -> println("Equal")
}
It prints Smaller because 5 < 10 is true, so that branch runs.
Click to reveal answer
What does a when without argument check in Kotlin?
AThe type of an object
BBoolean conditions in each branch
CThe value of a variable
DNothing, it always runs the first branch
What keyword is required to handle unmatched cases in a when without argument?
Afinally
Bdefault
Ccatch
Delse
What happens if no condition matches and there is no else branch in a when without argument?
AThe program continues silently
BThe first branch runs anyway
CA runtime exception is thrown
DThe program crashes at compile time
Which of these is a valid when without argument branch?
Ax == 5 -> println("Five")
B5 -> println("Five")
C"hello" -> println("Hello")
Delse if x == 5 -> println("Five")
Why use when without argument instead of if-else if?
AIt groups conditions clearly in one expression
BIt can check multiple variables at once
CIt is faster to run
DIt requires less code to write
Explain how a when expression without argument works in Kotlin and give a simple example.
Think about how you check multiple true/false questions one by one.
You got /3 concepts.
    What is the role of the else branch in a when without argument? What happens if it is missing?
    Consider what happens if no condition is true.
    You got /3 concepts.