Bird
Raised Fist0
Kotlinprogramming~10 mins

If as an expression returning value in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - If as an expression returning value
Evaluate condition
↓
Condition true?
No→Evaluate else branch
↓
Return else value
↓
Evaluate then branch
↓
Return then value
↓
Use returned value
The if expression evaluates a condition, then returns the value of the 'then' or 'else' branch accordingly.
Execution Sample
Kotlin
val max = if (a > b) a else b
println(max)
This code assigns the greater of a and b to max using if as an expression, then prints max.
Execution Table
StepCondition (a > b)Branch TakenReturned ValueOutput
15 > 3then5
2N/AN/A55
32 > 4else4
4N/AN/A44
53 > 3else3
6N/AN/A33
💡 Execution stops after returning value from if expression and printing it.
Variable Tracker
VariableStartAfter 1After 2After 3Final
a55233
b33433
maxunassigned5433
Key Moments - 3 Insights
Why does the if expression return a value instead of just running code?
Because in Kotlin, if is an expression that evaluates to the value of the branch taken, as shown in execution_table rows 1 and 3.
What happens if the condition is false and there is no else branch?
The code will not compile because if used as an expression must have an else branch to return a value, as implied by the need to return a value in all cases.
Can the returned value from if be assigned directly to a variable?
Yes, as shown in execution_table where max is assigned the returned value from the if expression.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the returned value when a=5 and b=3 at step 1?
A8
B5
C3
Dfalse
💡 Hint
Check the 'Returned Value' column at step 1 where condition is true.
At which step does the condition evaluate to false and the else branch is taken?
AStep 1
BStep 2
CStep 3
DStep 6
💡 Hint
Look at the 'Condition' and 'Branch Taken' columns in execution_table.
If we remove the else branch, what will happen when compiling this code?
AIt will cause a compile error
BIt will compile and run normally
CIt will return null
DIt will return zero
💡 Hint
Refer to key_moments about the necessity of else branch for if expressions.
Concept Snapshot
if expression syntax:
val result = if (condition) value1 else value2

- Evaluates condition
- Returns value1 if true
- Returns value2 if false
- Must have else branch when used as expression
- Can assign returned value directly to variable
Full Transcript
In Kotlin, if can be used as an expression that returns a value. The program checks the condition; if true, it evaluates and returns the 'then' branch value; if false, it evaluates and returns the 'else' branch value. This returned value can be assigned directly to a variable. The execution table shows examples with different values of a and b, demonstrating which branch is taken and what value is returned. Remember, when using if as an expression, you must include an else branch to cover all cases. This makes your code concise and expressive.

Practice

(1/5)
1. What does it mean when if is used as an expression in Kotlin?
easy
A. It returns a value that can be assigned to a variable.
B. It can only be used without an else block.
C. It cannot be used inside functions.
D. It always causes a syntax error.

Solution

  1. Step 1: Understand if as expression concept

    In Kotlin, if can return a value, unlike some other languages.
  2. Step 2: Recognize usage in assignments

    This means you can assign the result of an if expression directly to a variable.
  3. Final Answer:

    It returns a value that can be assigned to a variable. -> Option A
  4. Quick Check:

    if returns value = D [OK]
Hint: Remember: Kotlin's if returns a value, assignable to variables [OK]
Common Mistakes:
  • Thinking if cannot return values
  • Forgetting to include else block
  • Assuming if is only a statement
2. Which of the following is the correct syntax to assign the result of an if expression to a variable in Kotlin?
easy
A. val result if (x > 0) = "Positive" else "Non-positive"
B. val result = if (x > 0) "Positive" else "Non-positive"
C. val result = if (x > 0) { "Positive" }
D. val result = if x > 0 then "Positive" else "Non-positive"

Solution

  1. Step 1: Check correct Kotlin if expression syntax

    The correct syntax uses if (condition) value1 else value2 inside an assignment.
  2. Step 2: Identify errors in other options

    val result if (x > 0) = "Positive" else "Non-positive" has wrong order, C misses else, D uses invalid keywords.
  3. Final Answer:

    val result = if (x > 0) "Positive" else "Non-positive" -> Option B
  4. Quick Check:

    Correct syntax with else = A [OK]
Hint: Always include else and use parentheses in if expression [OK]
Common Mistakes:
  • Omitting else block
  • Wrong keyword order
  • Missing parentheses around condition
3. What is the output of the following Kotlin code?
val x = 5
val result = if (x % 2 == 0) "Even" else "Odd"
println(result)
medium
A. Even
B. 5
C. Odd
D. SyntaxError

Solution

  1. Step 1: Evaluate the condition x % 2 == 0

    Since 5 % 2 equals 1, the condition is false.
  2. Step 2: Determine which branch executes

    Because the condition is false, the else branch returns "Odd".
  3. Final Answer:

    Odd -> Option C
  4. Quick Check:

    5 is odd = C [OK]
Hint: Check condition result carefully to pick correct branch [OK]
Common Mistakes:
  • Assuming 5 is even
  • Ignoring else branch
  • Confusing modulo operation
4. Identify the error in this Kotlin code using if as an expression:
val x = 10
val result = if (x > 5) "Big"
medium
A. Incorrect variable declaration
B. Extra parentheses in if condition
C. Wrong comparison operator
D. Missing else branch for the if expression

Solution

  1. Step 1: Check if expression completeness

    When using if as an expression, Kotlin requires an else branch to cover all cases.
  2. Step 2: Identify missing else branch

    The code lacks an else branch, causing a compilation error.
  3. Final Answer:

    Missing else branch for the if expression -> Option D
  4. Quick Check:

    if expression needs else = B [OK]
Hint: Always add else when if returns a value [OK]
Common Mistakes:
  • Omitting else block
  • Assuming if can be incomplete
  • Ignoring compiler errors
5. You want to write a Kotlin function that returns "Positive", "Negative", or "Zero" based on an integer input using if as an expression. Which code correctly implements this?
hard
A. fun checkNumber(n: Int): String = if (n > 0) "Positive" else if (n < 0) "Negative" else "Zero"
B. fun checkNumber(n: Int): String { if (n > 0) return "Positive" else if (n < 0) return "Negative" else return "Zero" }
C. fun checkNumber(n: Int): String = if (n > 0) "Positive" else "Negative"
D. fun checkNumber(n: Int): String = if n > 0 then "Positive" else if n < 0 then "Negative" else "Zero"

Solution

  1. Step 1: Understand nested if as expression

    Kotlin allows nested if expressions to return values in a single expression.
  2. Step 2: Check each option for correctness

    fun checkNumber(n: Int): String = if (n > 0) "Positive" else if (n < 0) "Negative" else "Zero" correctly uses nested if expressions with proper syntax and returns all cases. fun checkNumber(n: Int): String { if (n > 0) return "Positive" else if (n < 0) return "Negative" else return "Zero" } uses statements, not expression style. fun checkNumber(n: Int): String = if (n > 0) "Positive" else "Negative" misses the zero case. fun checkNumber(n: Int): String = if n > 0 then "Positive" else if n < 0 then "Negative" else "Zero" uses invalid syntax.
  3. Final Answer:

    fun checkNumber(n: Int): String = if (n > 0) "Positive" else if (n < 0) "Negative" else "Zero" -> Option A
  4. Quick Check:

    Nested if expression with else = A [OK]
Hint: Use nested if-else expressions for multiple return values [OK]
Common Mistakes:
  • Missing else for zero case
  • Using statement style instead of expression
  • Incorrect syntax with then keyword
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard