Start learning free

LESSON 66 OF 348 · CONDITIONAL STATEMENTS

If Statements in Kotlin: Making Decisions with if and else

Lesson Read the full explanation

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    val isRainy = true
    if (isRainy) {
        println("I bring an umbrella")
    }
    



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast

I I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if (conditions) {
    // instructions
}

The keyword if tells Kotlin to execute the code inside the curly braces (where we have our Kotlin comment) only if the conditions defined in the parentheses are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

val isRainy = true
if (isRainy) {
    println("I bring an umbrella")
}

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true

But this code:

val amHungry = false
if (amHungry) {
    println("I have breakfast")
}

prints nothing since amHungry evaluates to false.


Assignment
Follow the Coding Tutorial and let's practice with if statements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · CONDITIONAL STATEMENTS

    If Statements in Kotlin, explained

    Why programs need decisions

    People decide things based on conditions all day: if it rains, take an umbrella; if you are hungry, eat. A program does the same with an if statement. It runs a block of code only when a condition is true, and skips it otherwise.

    val isRainy = true
    if (isRainy) {
        println("I bring an umbrella")
    }
    

    This prints I bring an umbrella. With val isRainy = false it prints nothing, because the block is skipped.

    The syntax

    if (condition) {
        // statements to run when the condition is true
    }
    
    • The keyword if starts the statement.
    • The condition goes in parentheses.
    • The block goes between curly braces. Everything inside runs only when the condition is true. Indent it by four spaces so the structure is easy to see.

    Boolean conditions

    The condition must be a Boolean, a value that is either true or false. It can be a Boolean variable, as above, or the result of a comparison such as age >= 18 or name == "Ana".

    Kotlin is strict about this. A number or a string is not a condition, and the compiler rejects it:

    val x = 5
    if (x) {   // does not compile
        println("yes")
    }
    
    error: condition type mismatch: inferred type is 'Int' but 'Boolean' was expected.
    

    Write the comparison you mean instead, for example if (x > 0).

    Adding else

    An else block holds the code that runs when the condition is false. It takes no condition of its own, because it covers every case the if did not:

    val isHungry = false
    if (isHungry) {
        println("I have breakfast")
    } else {
        println("I wait")
    }
    

    Exactly one of the two blocks runs, never both and never neither. The usual style puts } else { on one line, so the closing brace of the first block, the keyword and the opening brace of the second all sit together.

    The exercise

    The starter code declares val passed: Boolean = true. The lesson builds the statement in three steps.

    1. Write the if. The variable passed is already a Boolean, so it is the whole condition. Writing passed == true would work but adds nothing. Put it in parentheses and open the block with {.
    2. Print the success message inside the block. The text "Passed the test" goes in a println call, so it appears only when the condition holds.
    3. Add the else. Close the first block and open the second on the same line with } else {, print "Failed" inside it and close it with }. Now the program answers whichever value passed has.
    val passed: Boolean = true
    if (passed) {
        println("Passed the test")
    } else {
        println("Failed")
    }
    

    With passed set to true, the output is Passed the test. Change the first line to false and it becomes Failed.

    Checking more than two cases

    When two outcomes are not enough, chain further conditions with else if. Kotlin tests them from the top and runs the first block whose condition is true; the rest are skipped:

    val x = 5
    
    if (x > 10) {
        println("a")
    } else if (x > 3) {
        println("b")
    } else {
        println("c")
    }
    

    This prints b. Both x > 3 and the final else could apply to 5, but the chain stops at the first match. Order therefore matters: put the most specific condition first.

    Kotlin specifics

    In Kotlin, if is also an expression: it produces a value, so you can assign it. When used this way, the else is required, because the value has to exist in every case:

    val x = 5
    val size = if (x > 3) "big" else "small"
    println(size) // big
    

    Kotlin has no ternary ? : operator. This form takes its place. Without the else, val s = if (x > 3) "big" is a compile error: 'if' must have both main and 'else' branches when used as an expression.

    Common mistakes

    • Leaving out the parentheses. The condition always goes inside ( ).
    • Using a non-Boolean condition. if (x) with an Int fails to compile.
    • Trusting indentation instead of braces. Braces are optional when the body is one statement, but then only the next statement belongs to the if. In if (x > 3) followed by two lines, only the first line is conditional, and the second runs every time, however it is indented. Braces remove the doubt.
    • Using = for comparison. A single = assigns; use == to compare.
    • Putting a condition on else. else (x > 3) is not valid. To test another condition, write else if (x > 3) { ... }.

    Key takeaways

    • if (condition) { ... } runs its block only when the condition is true.
    • The condition must be a Boolean.
    • else { ... } runs when the condition is false.
    • In Kotlin, if can also produce a value, as long as it has an else.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free