Logical Operators
Logical operators join yes-or-no questions with words like and, or, and not. They help a program decide based on more than one fact at a time.
In this page:
Syntax
condition1 && condition2
condition1 || condition2
!condition
Logical Operators
Logical operators combine Boolean expressions: && (AND), || (OR), and ! (NOT). && and || short-circuit -- if the left side already determines the result, the right side is never evaluated.
This matters when the right side has side effects or could throw.
Note:
Short-circuiting lets you safely write
if (list.nonEmpty && list.head > 0) without risking an error on an empty list.Example: Logical Operators
object Main extends App {
val isLoggedIn = true
val isAdmin = false
println(isLoggedIn && isAdmin)
println(isLoggedIn || isAdmin)
println(!isAdmin)
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
&and|where&&and||are intended, so the right side is always evaluated. - Expecting
&&and||to evaluate both sides, when they short-circuit and skip the right side if the left decides the result. - Writing
!a == band expecting!(a == b), when!binds tighter.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: