Skip to main content
Kotlin Basics
CHAPTER 07 Beginner

Conditional Statements

Updated: May 18, 2026
5 min read

# CHAPTER 7

Conditional Statements

1. Chapter Introduction

Until now, our programs have executed sequentially, line by line. To build intelligent applications, our code needs to make decisions based on changing data. In this chapter, we will learn about Control Flow. We will explore standard if-else statements, learn how Kotlin treats if as an *expression* (meaning it can return a value!), and discover the incredibly powerful when construct, which replaces the clunky switch statement found in other languages.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use standard if, else if, and else statements.
  • Assign values dynamically using if as an Expression.
  • Use the when statement for multi-branch logic.
  • Replace Java's switch statement with when.
  • Build a Mini Project: Grade Calculator.

3. The if Statement

The if statement executes a block of code only if a specific condition evaluates to true.
kotlin
123456789
fun main() {
    val isRaining = true

    if (isRaining) {
        println("Take an umbrella!")
    } else {
        println("Wear sunglasses!")
    }
}

For multiple conditions, use else if:

kotlin
123456789
val score = 85

if (score >= 90) {
    println("Grade A")
} else if (score >= 80) {
    println("Grade B")
} else {
    println("Grade C or below")
}

4. if as an Expression (Kotlin Superpower)

In Java, if is a *statement* (it just performs an action). In Kotlin, if is an Expression—meaning it evaluates to a value that you can assign directly to a variable!

Because of this, Kotlin does not have a Ternary Operator (condition ? true : false). It doesn't need one!

kotlin
12345678910111213141516
fun main() {
    val a = 10
    val b = 20
    
    // Assigning the result of the if/else directly to the variable 'max'!
    val max = if (a > b) {
        a // Returns a
    } else {
        b // Returns b
    }

    println("The maximum value is $max")
    
    // Short, one-line version (Ternary equivalent):
    val min = if (a < b) a else b
}

*Note: If you use if as an expression, it MUST have an else branch.*

5. The when Expression

If you have a long chain of else if statements, the code gets very messy. Other languages use switch, but Kotlin uses the when expression, which is significantly more powerful.
kotlin
123456789101112
fun main() {
    val dayNumber = 3

    when (dayNumber) {
        1 -> println("Monday")
        2 -> println("Tuesday")
        3 -> println("Wednesday")
        4 -> println("Thursday")
        5 -> println("Friday")
        else -> println("Weekend or Invalid") // The 'else' acts like 'default'
    }
}

#### Advanced when Usage when can check multiple conditions, ranges, and even types!

kotlin
1234567891011
val age = 15

// Using when as an Expression (assigning result to a variable)
val status = when (age) {
    in 0..12 -> "Child"         // Check if age is in a range (0 to 12)
    13, 14, 15 -> "Young Teen"  // Match multiple specific values
    in 16..19 -> "Teenager"
    else -> "Adult"
}

println("Status: $status")

6. Mini Project: Grade Calculator

Let's build a dynamic grade calculator that asks for a score and uses a when expression to assign a letter grade.
kotlin
123456789101112131415
fun main() {
    print("Enter student score (0-100): ")
    val score = readln().toIntOrNull() ?: 0

    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89  -> "B"
        in 70..79  -> "C"
        in 60..69  -> "D"
        in 0..59   -> "F"
        else -> "Invalid Score"
    }

    println("Final Grade: $grade")
}

7. Common Mistakes

  • Forgetting else in Expressions: If you assign the result of an if or when to a variable, you MUST provide an else branch. The compiler needs a guarantee that the variable will definitely receive *some* value.
  • Using Java's switch: Kotlin does not have the switch keyword. Attempting to use it will result in a syntax error.

8. Best Practices

  • Prefer when over else if: If you have more than two branches of logic checking the same variable, always use when. It is vastly more readable.
  • Single-line logic: Use the inline if expression (val res = if (x) a else b) instead of creating a mutable var and assigning it inside standard if/else blocks.

9. Exercises

  1. 1. Write a program that asks for the user's current temperature.
  1. 2. Use an if expression to assign a String variable clothing.
  1. 3. If temp > 25, clothing = "T-Shirt". Else, clothing = "Jacket".
  1. 4. Print the result.

10. MCQs with Answers

Question 1

What keyword is used to execute code only if a condition is true?

Question 2

In Kotlin, if can be used as an Expression. What does this mean?

Q3. Does Kotlin have a Ternary Operator (e.g., condition ? a : b)? a) Yes b) No, because if/else can be used as an expression on a single line Answer: b) No.
Question 4

If you use if as an expression to assign a variable, what is strictly required?

Question 5

What construct in Kotlin replaces the Java switch statement?

Question 6

What keyword acts as the "default" case inside a when block?

Q7. Can a when expression check if a number is inside a range? a) Yes, using the in keyword (e.g., in 1..10) b) No Answer: a) Yes.

Q8. Can a single branch in a when expression match multiple values? a) Yes, by separating them with commas (e.g., 1, 2, 3 ->) b) No Answer: a) Yes.

Q9. Like if, can when be used as an expression to assign a variable? a) Yes b) No Answer: a) Yes.

Question 10

If checking multiple ranges inside when(score), which branch executes?

11. Interview Questions

  • Q: Explain how Kotlin's if expression eliminates the need for a ternary operator. Provide a code example.
  • Q: Compare Java's switch statement with Kotlin's when expression. Why is when considered superior? (Answer: when doesn't require break statements, prevents fall-through bugs, can be used as an expression, and supports complex range/type checking).

12. Summary

Control flow is what makes an application "smart." By turning if and when into Expressions that return values, Kotlin drastically reduces the need for mutable var variables, leading to cleaner and safer code. The when expression is one of Kotlin's most beloved features, making complex multi-branch logic a joy to read.

13. Next Chapter Recommendation

Our code can make decisions, but it still only runs once. What if we want to do something 100 times? In Chapter 8: Loops in Kotlin, we will explore how to repeat tasks efficiently using for and while loops, and dive deeper into Kotlin Ranges.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·