Kotlin If with OR operator

Kotlin If with OR Logical Operator

In Kotlin, you can use the if statement with the || (logical OR) operator to evaluate multiple conditions where at least one of the conditions needs to be true to execute a block of code.

Syntax of If statement with OR operator

The syntax to use OR operator to combine two simple conditions is given below.

if (condition1 || condition2) {
    // Code to execute if at least one of the conditions is true
} else {
    // Code to execute if both conditions are false
}

Example for If statement with OR operator

In this example, we shall write an if-statement, where we check if given day is a weekend or holiday.

Main.kt

fun main() {
    val isWeekend = true
    val isHoliday = false

    if (isWeekend || isHoliday) {
        println("It's a day off!")
    } else {
        println("It's a regular workday.")
    }
}

Output

It's a day off!

In this example, the if statement checks two conditions:

  1. isWeekend: Checks if it’s a weekend.
  2. isHoliday: Checks if it’s a holiday.

If at least one of the conditions is true, the code inside the if block will execute. If both conditions are false, the code inside the else block will execute.

Summary

In this tutorial, we have seen how to use OR logical operator to combine two simple conditions to form a compound condition and use it in an if-else statement, with examples.