🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Logical Operators

Logical operators combine Boolean values into one Boolean result. They let one stored result cover two or more facts at once.

&& needs both sides true

Both sides true gives true. One false side is enough to make the whole result false.

@main def main(): Unit =
  val both = true && true
  val oneMissing = true && false
  println(both)
  println(oneMissing)

|| needs only one side true

One true side makes the result true. The result is false only when both sides are false.

@main def main(): Unit =
  val weekend = false
  val holiday = true
  val dayOff = weekend || holiday
  println(dayOff)
  println(false || false)

! flips a value

The ! sign turns true into false and false into true. It can also join a bigger check with &&.

@main def main(): Unit =
  val isRaining = false
  val isCold = true
  println(!isRaining)
  println(!isCold)
  println(!isRaining && isCold)

Example

@main def main(): Unit =
  val age = 25
  val ageOk = age >= 18
  val hasTicket = true
  val allowed = ageOk && hasTicket
  println(allowed)
  println(ageOk && !hasTicket)
  println(!ageOk || hasTicket)

Key points

  • And: && gives true only when both sides are true.
  • Or: || gives true when at least one side is true.
  • Not: ! flips true to false and false to true.
  • Stored results: a combined result can be stored in a val like any other value.
  • Grouped checks: parentheses show which parts combine first.

In this example, ageOk is true because 25 >= 18 is true, and hasTicket is true. Joining them with && gives true, while && with !hasTicket gives false because !hasTicket is false. The last line is true because hasTicket is true, and || needs only one true side.

Note

&& and || work on Boolean values, not on numbers or text.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does println(true || false && false) print? Hint: && runs before ||.