How to Use Logical Operators in Kotlin: Syntax and Examples
In Kotlin, use
&& for logical AND, || for logical OR, and ! for logical NOT. These operators combine or invert Boolean expressions to control program flow.Syntax
Kotlin uses three main logical operators:
&&: Returns true if both conditions are true.||: Returns true if at least one condition is true.!: Inverts the Boolean value (true becomes false, false becomes true).
kotlin
val a = true val b = false val andResult = a && b // false val orResult = a || b // true val notResult = !a // false
Example
This example shows how to use logical operators to check multiple conditions and print results accordingly.
kotlin
fun main() {
val isSunny = true
val hasUmbrella = false
if (isSunny && !hasUmbrella) {
println("It's sunny and you don't have an umbrella.")
} else if (!isSunny || hasUmbrella) {
println("Either it's not sunny or you have an umbrella.")
} else {
println("Conditions are unclear.")
}
}Output
It's sunny and you don't have an umbrella.
Common Pitfalls
Common mistakes include using single & or | instead of double && or || for logical operations, which perform bitwise operations instead of Boolean logic. Also, forgetting to use parentheses can cause unexpected results due to operator precedence.
kotlin
fun main() {
val x = true
val y = false
// Wrong: bitwise AND instead of logical AND
val wrong = x & y
println("Wrong result: $wrong") // false but not recommended
// Correct: logical AND
val correct = x && y
println("Correct result: $correct") // false
// Without parentheses, this can be confusing
val result = x || y && !x // && has higher precedence
println("Result without parentheses: $result")
// Better with parentheses
val clearResult = (x || y) && !x
println("Result with parentheses: $clearResult")
}Output
Wrong result: false
Correct result: false
Result without parentheses: true
Result with parentheses: false
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| && | Logical AND | true && false | false |
| || | Logical OR | true || false | true |
| ! | Logical NOT | !true | false |
Key Takeaways
Use && for AND, || for OR, and ! for NOT to combine or invert Boolean values.
Double operators (&&, ||) are for logic; single (&, |) are bitwise and usually not what you want.
Use parentheses to clarify complex logical expressions and avoid precedence errors.
Logical operators help control program decisions by combining multiple conditions.
Test your conditions carefully to avoid unexpected true/false results.