Start learning free

LESSON 79 OF 348 · CONDITIONAL STATEMENTS

Combining Logical Operators in Scala

Lesson

Sometimes we need to combine logical operators to evaluate more complex conditions. For example:

7 >= 10 && (5 == 7 || 9 < 12) // Evaluates to false

Notice that we used parentheses to group 5 == 7 and 9 < 12 together. The computer interprets this line of code as condition1 && condition2 where:

  • condition1 is 7 >= 10, which is false
  • condition2 is (5 == 7 || 9 < 12), which is true
At least one of condition1 and condition2 is false, so the entire condition is false.

It is very important to use parentheses to tell the computer how to group the conditions together. If we change the parentheses in the example above to:

(7 >= 10 && 5 == 7) || 9 < 12 // Evaluates to true

Now the computer interprets this line of code as condition1 || condition2 where:

  • condition1 is (7 >= 10 && 5 == 7), which is false
  • condition2 is 9 < 12, which is true
At least one of condition1 and condition2 is true, so the entire condition is true.

Assignment
Follow the Coding Tutorial and let's combine some logical operators.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    Combining Logical Operators in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free