Write conditionals in Kotlin¶

Before you begin¶

  • This codelab teaches you how to use the if/else and when statements and expressions to write conditionals in Kotlin.

Prerequisites¶

  • Knowledge of Kotlin programming basics, including variables, and the println() and main() functions

What you’ll learn¶

  • How to write boolean expressions.

  • How to write if/else statements.

  • How to write when statements.

  • How to write if/else expressions.

  • How to write when expressions.

  • How to use commas to define common behavior for multiple branches in when conditionals.

  • How to use the in range to define common behavior for a range of branches in when conditionals.

  • How to use the is keyword to write when conditional statements.

What you’ll need¶

  • A web browser with access to Kotlin Playground.

Use if/else statements to express conditions¶

  • In Kotlin, the syntax for an if statement is:

    if (condition1) {
        // code to execute if condition1 is true
    } else if (condition2) {
        // code to execute if condition2 is false
    } else if (condition3) {
        // code to execute if condition3 is false
    } else {
        // code to execute if condition is false
    }
    

Use a when statement for multiple branches¶

  • In Kotlin, when you deal with multiple branches, you can use the when statement instead of the if/else statement because it improves readability. It’s very important to consider readability when you write your code because it’s likely that other developers need to review and modify your code throughout its lifetime. Good readability ensures that developers can correctly understand your code and don’t inadvertently introduce bugs into it.

  • when statements are preferred when there are more than two branches to consider.

    ../_images/unit2-pathway1-activity2-section3-2f7c0a1e312a2581_1440.png
  • A when statement accepts a single value through the parameter. The value is then evaluated against each of the conditions sequentially. The corresponding body of the first condition that’s met is then executed. Each condition and body are separated by an arrow (->). Similar to if/else statements, each pair of condition and body is called a branch in when statements. Also similar to the if/else statement, you can add an else branch as your final condition in a when statement that works as a catchall branch.

  • Examples:

    fun main() {
        val trafficLightColor = "Black"
    
        when (trafficLightColor) {
            "Red" -> println("Stop")
            "Yellow" -> println("Slow")
            "Green" -> println("Go")
            else -> println("Invalid traffic-light color")
        }
    }
    
    fun main() {
        val x = 3
    
        when (x) {
            2 -> println("x is a prime number between 1 and 10.")
            3 -> println("x is a prime number between 1 and 10.")
            5 -> println("x is a prime number between 1 and 10.")
            7 -> println("x is a prime number between 1 and 10.")
            else -> println("x isn't a prime number between 1 and 10.")
        }
    }
    
  • Use a comma (,) to denote multiple conditions that correspond to the same body.

    ../_images/unit2-pathway1-activity2-section3-4e778c4c4c044e51_1440.png
  • Example:

    fun main() {
        val x = 3
    
        when (x) {
            2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
            else -> println("x isn't a prime number between 1 and 10.")
        }
    }
    
  • Use the in keyword and a range of values in when branches.

    ../_images/unit2-pathway1-activity2-section3-400f940f363bd3c4_1440.png
    fun main() {
        val x = 3
    
        when (x) {
            2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
            in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
            else -> println("x isn't a prime number between 1 and 10.")
        }
    }
    
  • Use the is keyword as a condition to check the data type of an evaluated value.

    ../_images/unit2-pathway1-activity2-section3-66841365125b37aa_1440.png
    fun main() {
        val x: Any = 20
    
        when (x) {
            2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
            in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
            is Int -> println("x is an integer number, but not between 1 and 10.")
            else -> println("x isn't an integer number.")
        }
    }
    

Use if/else and when as expressions¶

  • You can also use conditionals as expressions to return different values for each branch of condition. When the body of each branch appears similar, you can use conditional expressions to improve code readability compared to conditional statements.

    ../_images/unit2-pathway1-activity2-section4-a6ff7ba09d3cdea3_1440.png
  • If the bodies only contain a return value or expression, you can remove the curly braces to make the code more concise.

    fun main() {
        val trafficLightColor = "Black"
    
        val message =
            if (trafficLightColor == "Red") "Stop"
            else if (trafficLightColor == "Yellow") "Slow"
            else if (trafficLightColor == "Green") "Go"
            else "Invalid traffic-light color"
    
        println(message)
    }
    
    fun main() {
        val trafficLightColor = "Amber"
    
        val message = when(trafficLightColor) {
            "Red" -> "Stop"
            "Yellow", "Amber" -> "Slow"
            "Green" -> "Go"
            else -> "Invalid traffic-light color"
        }
        println(message)
    }
    

    Note

    A when statement doesn’t need the else branch to be defined. However, in most cases, a when expression requires the else branch because the when expression needs to return a value. As such, the Kotlin compiler checks whether all the branches are exhaustive. An else branch ensures that there won’t be a scenario in which the variable doesn’t get assigned a value.

Conclusion¶

  • In Kotlin, branching can be achieved with if/else or when conditionals.

  • It’s recommended to use the when conditional to replace an if/else conditional when there are more than two branches.

  • You can write more complex conditions in when conditionals with the comma (,), in ranges, and the is keyword.

  • if/else and when conditionals can work as either statements or expressions.