๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin If Else

An if statement runs a block of code only when its condition is true. An else block runs when that condition is false.

Running a block when true

A block is a group of code inside braces. The block runs only when the condition is true, and the print after it runs either way.

fun main() {
    val score = 80
    if (score >= 50) {
        println("Pass")
    }
    println("Checked")
}

Else covers the false case

The condition is false for this score. The else block runs and the if block stays unused.

fun main() {
    val score = 40
    if (score >= 50) {
        println("Pass")
    } else {
        println("Fail")
    }
}

Else if chains

The chain tests its conditions from the top. This score passes the second test and prints its letter.

fun main() {
    val score = 65
    if (score >= 90) {
        println("A")
    } else if (score >= 60) {
        println("B")
    } else {
        println("C")
    }
}

If gives a value

An expression is a piece of code that gives a value. The whole if stands on the right side of the equals sign, and the chosen word is stored and then printed.

fun main() {
    val score = 72
    val label = if (score >= 60) "Pass" else "Fail"
    println(label)
}

Example

fun main() {
    val score = 82
    val label = if (score >= 60) "Pass" else "Fail"
    println(label)
    if (score >= 90) {
        println("A")
    } else if (score >= 80) {
        println("B")
    } else {
        println("C")
    }
}

Key points

  • Use if to run a block when a condition is true.
  • Use else to run a block when the same condition is false.
  • Use else if to test a new condition when the first one is false.
  • The condition must be a Boolean value.
  • A program never guesses true or false from a number.
  • Use an if as a value to store the chosen result in a val.

In this example, score holds 82. The if expression gives Pass because score >= 60 is true, and the first print shows Pass. The chain then tests score >= 90 and finds it false. The else if test score >= 80 is true, so the program prints B.

Note

Kotlin has no separate ? : sign for this choice. The if itself gives the value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

A program sets score to 45 and stores if (score >= 50) "Pass" else "Fail" in a val. What is stored?