Kotlin If with AND operator

Kotlin If with AND Logical Operator

In Kotlin, you can use the if statement with the && (logical AND) operator to evaluate multiple conditions. The && operator allows you to check if multiple conditions are all true before executing a block of code.

Syntax of If statement with AND operator

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

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

Example for If statement with AND operator

In this example, we shall write an if-statement, where we check if the age of the person is greater than or equal to 18 and the person has license.

Main.kt

fun main() {
    val age = 25
    val hasLicense = true

    if (age >= 18 && hasLicense) {
        println("You are eligible to drive.")
    } else {
        println("You are not eligible to drive.")
    }
}

Output

You are eligible to drive.

In this example, the if statement checks two conditions:

  1. age >= 18: Checks if the person is at least 18 years old.
  2. hasLicense: Checks if the person has a driver’s license.

Both conditions must be true for the code inside the if block to execute. If either of the conditions is false, the code inside the else block will execute.

Summary

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