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?✗ Incorrect
When using
if as an expression, Kotlin requires an else branch to ensure a value is always returned.What does this Kotlin code return?<br>
val result = if (x > 0) "Positive" else "Non-positive"
✗ Incorrect
The
if expression returns a String depending on the condition.Which of these is a valid use of
if as an expression in Kotlin?✗ Incorrect
Option C includes both
if and else branches, making it a valid expression that returns a value.What type will Kotlin infer for this expression?<br>
val x = if (flag) 10.0 else 20.5
✗ Incorrect
Kotlin infers the common supertype, which is
Double because both 10.0 and 20.5 are Doubles.Why is
if as an expression useful in Kotlin?✗ Incorrect
If as an expression lets you write cleaner code by assigning values directly based on conditions.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.