0
0
Kotlinprogramming~15 mins

If as an expression returning value in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - If as an expression returning value
What is it?
In Kotlin, the 'if' statement can be used as an expression that returns a value. This means you can assign the result of an 'if' directly to a variable. Unlike many languages where 'if' is only a control flow statement, Kotlin treats it as an expression that produces a result based on the condition.
Why it matters
Using 'if' as an expression makes code shorter and clearer by combining decision-making and value assignment in one step. Without this, you would need extra lines to declare variables and assign values inside each branch, making code longer and harder to read.
Where it fits
Before learning this, you should understand basic Kotlin syntax, variables, and control flow statements. After this, you can explore more advanced expressions like 'when' expressions and lambda functions.
Mental Model
Core Idea
'If' in Kotlin is like a question that immediately gives you an answer you can use right away.
Think of it like...
Imagine asking a friend, 'Should I wear a jacket?' and they immediately say 'Yes' or 'No'—you get the answer right away without extra steps.
┌───────────────┐
│   Condition   │
└──────┬────────┘
       │ true
       ▼
  ┌───────────┐
  │  Value A  │
  └───────────┘
       │
       └─────┐
             │
          false
             ▼
       ┌───────────┐
       │  Value B  │
       └───────────┘

Result: Value A if true, else Value B
Build-Up - 7 Steps
1
FoundationBasic if statement usage
🤔
Concept: Learn how to use a simple 'if' statement to control program flow.
val number = 10 if (number > 5) { println("Number is greater than 5") } else { println("Number is 5 or less") }
Result
Number is greater than 5
Understanding how 'if' controls which code runs is the first step before using it as a value.
2
FoundationVariable assignment basics
🤔
Concept: Learn how to assign values to variables in Kotlin.
val greeting: String greeting = "Hello" println(greeting)
Result
Hello
Knowing how to store values in variables prepares you to assign 'if' expression results.
3
IntermediateIf as an expression example
🤔Before reading on: do you think 'if' can return a value directly in Kotlin? Commit to yes or no.
Concept: Introduce 'if' as an expression that returns a value which can be assigned to a variable.
val max = if (10 > 5) 10 else 5 println(max)
Result
10
Understanding that 'if' can produce a value lets you write concise and expressive code.
4
IntermediateUsing if expression with blocks
🤔Before reading on: can 'if' expression use multiple lines inside its branches? Guess yes or no.
Concept: Show that 'if' expression branches can be blocks with multiple statements, returning the last value.
val result = if (10 % 2 == 0) { println("Even number") "Even" } else { println("Odd number") "Odd" } println(result)
Result
Even number Even
Knowing that blocks return the last expression value allows complex logic inside 'if' expressions.
5
IntermediateNullable values with if expression
🤔
Concept: Use 'if' expression to assign nullable values safely.
val input: String? = null val length = if (input != null) input.length else 0 println(length)
Result
0
Using 'if' expressions helps handle nullability clearly and safely.
6
AdvancedNested if expressions
🤔Before reading on: do nested 'if' expressions return the innermost value or something else? Commit your answer.
Concept: Learn how to nest 'if' expressions to handle multiple conditions and return values accordingly.
val score = 85 val grade = if (score >= 90) { "A" } else if (score >= 80) { "B" } else { "C" } println(grade)
Result
B
Understanding nested 'if' expressions lets you handle complex decision trees in a clean way.
7
ExpertIf expression in inline functions
🤔Before reading on: can 'if' expressions be used in single-expression functions? Guess yes or no.
Concept: Use 'if' expressions to write concise single-expression functions that return values directly.
fun max(a: Int, b: Int) = if (a > b) a else b println(max(3, 7))
Result
7
Knowing that 'if' expressions enable concise function definitions improves code readability and efficiency.
Under the Hood
Kotlin treats 'if' as an expression by evaluating the condition and then evaluating exactly one branch to produce a value. The value of the last expression in the chosen branch becomes the result. This is possible because Kotlin's syntax and compiler support expressions everywhere, unlike languages where 'if' is only a statement.
Why designed this way?
Kotlin was designed to be concise and expressive, reducing boilerplate code. Making 'if' an expression allows combining decision-making and value assignment, which was cumbersome in Java and other languages. This design choice improves readability and reduces errors from uninitialized variables.
┌───────────────┐
│ Evaluate cond │
└──────┬────────┘
       │ true
       ▼
  ┌─────────────┐
  │ Evaluate A  │
  └──────┬──────┘
         │
         ▼
   Return A value
       │
       └─────┐
             │
          false
             ▼
  ┌─────────────┐
  │ Evaluate B  │
  └──────┬──────┘
         │
         ▼
   Return B value
Myth Busters - 4 Common Misconceptions
Quick: Does Kotlin's 'if' expression always require an 'else' branch? Commit yes or no.
Common Belief:You can use 'if' as an expression without an 'else' branch.
Tap to reveal reality
Reality:In Kotlin, 'if' used as an expression must have an 'else' branch to cover all cases, otherwise it won't compile.
Why it matters:Missing 'else' causes compilation errors and forces you to handle all cases explicitly, preventing bugs from unhandled conditions.
Quick: Does the 'if' expression evaluate both branches before choosing one? Commit yes or no.
Common Belief:Both branches of an 'if' expression are evaluated before the result is chosen.
Tap to reveal reality
Reality:Only the branch matching the condition is evaluated; the other branch is skipped entirely.
Why it matters:Knowing this prevents unexpected side effects and performance issues from evaluating unnecessary code.
Quick: Can you use 'if' expression to return different types in branches without error? Commit yes or no.
Common Belief:Branches of an 'if' expression can return different types without problems.
Tap to reveal reality
Reality:All branches must return compatible types so the compiler can infer a single type for the expression.
Why it matters:Ignoring this causes type errors and confusion about what value the expression produces.
Quick: Is 'if' expression the same as 'when' expression in Kotlin? Commit yes or no.
Common Belief:'If' expression and 'when' expression are interchangeable in all cases.
Tap to reveal reality
Reality:'If' is for simple two-way decisions; 'when' handles multiple conditions more cleanly and is more powerful.
Why it matters:Using 'if' for many conditions leads to messy code; knowing when to use 'when' improves clarity and maintainability.
Expert Zone
1
The type inferred for an 'if' expression is the common supertype of all branch results, which can sometimes be 'Any' if branches differ widely.
2
Using 'if' expressions inside inline functions can improve performance by avoiding unnecessary object creation.
3
Kotlin's smart casting works seamlessly with 'if' expressions, allowing safe access to variables after null checks within branches.
When NOT to use
Avoid using 'if' expressions when the branches involve complex side effects or when multiple conditions are better expressed with 'when' expressions. For very complex logic, traditional statements or polymorphism may be clearer.
Production Patterns
In production, 'if' expressions are often used for concise value assignments, especially in single-expression functions, default parameter values, and lambda expressions. They help reduce boilerplate and improve readability in configuration and UI code.
Connections
Ternary operator (?:) in other languages
'If' expression in Kotlin builds on the same idea as the ternary operator in languages like Java or C, but is more flexible.
Understanding Kotlin's 'if' expression clarifies how it replaces the ternary operator with a more readable and powerful construct.
Functional programming expressions
'If' as an expression aligns with functional programming where everything is an expression returning a value.
Knowing this helps learners appreciate Kotlin's design for immutability and expression-oriented style.
Decision making in human psychology
Both involve evaluating conditions and choosing an outcome based on criteria.
Recognizing this connection helps understand how programming models human decision processes logically and predictably.
Common Pitfalls
#1Forgetting the 'else' branch in an 'if' expression.
Wrong approach:val result = if (x > 0) "Positive"
Correct approach:val result = if (x > 0) "Positive" else "Non-positive"
Root cause:Misunderstanding that 'if' as an expression must cover all cases to produce a value.
#2Returning different types in 'if' branches causing type errors.
Wrong approach:val value = if (flag) 10 else "Ten"
Correct approach:val value = if (flag) 10 else 0
Root cause:Not realizing Kotlin requires a common type for all branches of an expression.
#3Using 'if' expression when side effects are needed but ignored.
Wrong approach:val result = if (condition) doSomething() else doSomethingElse()
Correct approach:if (condition) doSomething() else doSomethingElse()
Root cause:Confusing expressions that return values with statements that perform actions.
Key Takeaways
'If' in Kotlin is an expression that returns a value, allowing concise and clear code.
Every 'if' expression must have an 'else' branch to cover all cases and compile successfully.
Only the branch matching the condition is evaluated, preventing unnecessary work or side effects.
All branches must return compatible types so the compiler can infer a single result type.
Using 'if' expressions enables writing concise single-expression functions and cleaner assignments.