Start learning free

LESSON 67 OF 348 · CONDITIONAL STATEMENTS

If-Else Statements in Kotlin

Lesson Read the full explanation

Many times in our life, not only we choose to do something if a condition is met, but also choose to do something different if that condition is not met. For example:

If I'm tired:
    I take a nap
Otherwise:
    I start coding

If-else Statements:

When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen.

With an else statement, we can have an alternate block of code to be executed. For example:

val amTired: Boolean = false
if (amTired) {
    println("I take a nap")
} else {
    println("I start coding")
}

The code above prints "I start coding" since the expression inside the if evaluates to false and so Kotlin will enter the else statement and execute the code inside it.

An else statement cannot exist without a corresponding if statement. This combination is refered to as an if-else statement.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · CONDITIONAL STATEMENTS

    If Else in Kotlin, explained

    What if-else does

    An if statement runs a block of code only when its condition is true. When the condition is false, the block is skipped and nothing happens. Often that isn't enough: you want one thing to happen when the condition holds and a different thing when it doesn't. That is what else adds.

    In plain words: if I'm tired, I take a nap, otherwise I start coding. In Kotlin:

    val amTired: Boolean = false
    if (amTired) {
        println("I take a nap")
    } else {
        println("I start coding")
    }
    

    Because amTired is false, Kotlin skips the first block and runs the one after else. The program prints I start coding. Exactly one of the two blocks runs, never both and never neither.

    The syntax

    • The condition goes in parentheses after if, and it must be a Boolean.
    • Each branch is a block in curly braces.
    • else has no condition and no parentheses. It runs whenever the if condition was false.
    • else can't stand alone. It always belongs to the if right before it.

    The convention is to write else on the same line as the } that closes the if block, as in } else {.

    The exercise

    The lesson starts with an if and no else:

    val passed: Boolean = false
    if (passed) {
        println("Passed the test")
    }
    

    Since passed is false, this program prints nothing at all. The task is to make it report a result in that case too. Attach an else branch to the existing block and print "Failed the test" inside it:

    val passed: Boolean = false
    if (passed) {
        println("Passed the test")
    } else {
        println("Failed the test")
    }
    

    Now the output is Failed the test. Change passed to true and the first branch runs instead, printing Passed the test. Try both values in the editor above to see each branch run.

    if-else as an expression

    In Kotlin, if is an expression: it produces a value, so you can assign its result. When you use it that way, else is required, because the expression needs a value for both outcomes:

    val amTired = false
    val plan = if (amTired) "nap" else "code"
    println(plan)
    

    This prints code. For this lesson the statement form with blocks is what you need, but the expression form is how Kotlin replaces the ternary operator found in other languages.

    Braces and indentation

    Kotlin lets you drop the braces when a branch holds a single statement, as in if (passed) println("Passed") else println("Failed"). Keep the braces while you are learning. They make it obvious which lines belong to which branch, and adding a second statement later won't silently fall outside the branch. Indent the code inside each block by four spaces. The compiler ignores indentation, but it lets a reader see the structure at a glance.

    More than two outcomes

    When two branches aren't enough, chain further checks with else if. Kotlin tests the conditions from top to bottom and runs the first block whose condition is true. The final else catches everything that is left:

    val hour = 20
    if (hour < 12) {
        println("Morning")
    } else if (hour < 18) {
        println("Afternoon")
    } else {
        println("Evening")
    }
    

    With hour equal to 20, both conditions are false, so the program prints Evening. Once one branch has run, the rest of the chain is skipped.

    Common mistakes

    • Putting a condition on else. Writing else (passed == false) is an error. If you need a further test, use else if, which is a new if inside the else.
    • Using a non-Boolean condition. Kotlin doesn't treat numbers or strings as true or false. if (x) with an Int x is a compile error: condition type mismatch, inferred type is Int but Boolean was expected.
    • Writing = instead of ==. = assigns and == compares. An assignment isn't allowed inside the condition, so Kotlin reports an error rather than quietly accepting it.

    Key takeaways

    • if runs a block when its condition is true; else runs a block when it is false.
    • Exactly one of the two branches runs.
    • else has no condition and always pairs with an if.
    • Conditions must be Boolean in Kotlin.
    • if (...) a else b can also be used as a value.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free