0
0
Kotlinprogramming~5 mins

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

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean that if is an expression in Kotlin?
In Kotlin, if can return a value, so you can assign the result of an if expression directly to a variable.
Click to reveal answer
beginner
How do you assign a value using if as an expression?
You write val result = if (condition) value1 else value2. The variable result gets the value from the branch that runs.
Click to reveal answer
intermediate
Can if expression in Kotlin have no else branch?
No, if you use if as an expression to return a value, you must include an else branch to cover all cases.
Click to reveal answer
intermediate
What type does an if expression return?
The if expression returns a value of the common supertype of all branches. For example, if one branch returns Int and another Double, the result type will be Double.
Click to reveal answer
beginner
Show a simple Kotlin example using if as an expression.
Example:<br>
val max = if (a > b) a else b
<br>This assigns the greater of a or b to max.
Click to reveal answer
In Kotlin, what must you include when using if as an expression to assign a value?
AAn else branch
BOnly the if branch
CA loop
DA return statement
What does this Kotlin code return?<br>
val result = if (x > 0) "Positive" else "Non-positive"
AA Boolean value
BNo value
CAn Int value
DA String value
Which of these is a valid use of if as an expression in Kotlin?
Aif (a > b) a else b
Bval x = if (a > b) a
Cval x = if (a > b) a else b
Dif (a > b) { a }
What type will Kotlin infer for this expression?<br>
val x = if (flag) 10.0 else 20.5
AInt
BDouble
CString
DBoolean
Why is if as an expression useful in Kotlin?
AIt allows assigning values directly from conditions.
BIt replaces loops.
CIt is faster than statements.
DIt can only be used with numbers.
Explain how if as an expression works in Kotlin and why it requires an else branch.
Think about how Kotlin needs a value no matter what condition happens.
You got /3 concepts.
    Write a Kotlin example using if as an expression to assign the smaller of two numbers to a variable.
    Use <code>if (a < b) a else b</code> pattern.
    You got /3 concepts.