0
0
Kotlinprogramming~5 mins

When as expression returning value in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a when expression in Kotlin?
A when expression in Kotlin is a control structure that checks a value against multiple conditions and returns a result based on the first matching condition.
Click to reveal answer
beginner
How do you use when as an expression to return a value?
You assign the when expression to a variable. Each branch returns a value, and the whole when expression evaluates to that value.
Click to reveal answer
intermediate
What happens if no branch matches in a when expression used as a value?
If no branch matches, and there is no else branch, the code will not compile. You must provide an else branch to cover all cases.
Click to reveal answer
intermediate
Can when expression branches return different types?
No. All branches must return values of the same type or compatible types so the when expression has a consistent return type.
Click to reveal answer
beginner
Example: What is the value of result after this code?<br>
val x = 2
val result = when (x) {
  1 -> "One"
  2 -> "Two"
  else -> "Other"
}
The value of result is "Two" because the when expression matches the case 2 and returns "Two".
Click to reveal answer
What must a when expression used as a value always include?
AA <code>break</code> statement
BA loop inside each branch
CA <code>return</code> keyword in each branch
DAn <code>else</code> branch to cover unmatched cases
What type of value does a when expression return?
AThe type common to all branch results
BThe type of the first branch only
CAlways a String
DNo value, it returns Unit
What happens if you omit the else branch in a when expression used as a value?
AThe program compiles but throws an error at runtime
BThe program does not compile
CThe first branch is used as default
DThe program compiles and returns null
Which of these is a valid way to assign a value using when expression?
Aval result = when (x) { 1: 10, 2: 20 }
Bval result = when (x) { 1 -> 10; 2 -> 20 }
Cval result = when (x) { 1 -> 10 2 -> 20 else -> 0 }
Dval result = when (x) { 1 => 10, 2 => 20 }
Can a when expression be used without an argument?
AYes, it can check arbitrary conditions in branches
BNo, it always requires an argument
COnly if used inside a function
DOnly with numeric arguments
Explain how a when expression returns a value in Kotlin and why the else branch is important.
Think about how the program decides what value to give back.
You got /4 concepts.
    Describe the rules for the types of values returned by each branch in a when expression used as a value.
    Consider what happens if branches return different kinds of values.
    You got /4 concepts.