Scala - Logical Operators Example

1. Introduction

Logical operators are a cornerstone of programming logic, allowing you to combine multiple conditions. Scala supports all the standard logical operators found in many other programming languages. This blog post will introduce Scala's logical operators and show how to use them with examples.

Scala - Logical Operators

Scala provides the following logical operators to form compound Boolean expressions:

&& (Logical AND): Returns true if both operands are true.

|| (Logical OR): Returns true if at least one of the operands is true.

! (Logical NOT): Returns the inverse of the Boolean value.

2. Program Steps

1. Define Boolean variables for comparison.

2. Use logical operators to combine these variables into logical expressions.

3. Print the results of the logical operations.

4. Execute the program to observe the Boolean outcomes.

3. Code Program

object LogicalOperatorsDemo extends App {
  val cond1: Boolean = true
  val cond2: Boolean = false

  // Logical AND
  println(s"cond1 && cond2: " + (cond1 && cond2))
  // Logical OR
  println(s"cond1 || cond2: " + (cond1 || cond2))
  // Logical NOT
  println(s"!cond1: " + (!cond1))
  println(s"!cond2: " + (!cond2))
}

Output:

cond1 && cond2: false
cond1 || cond2: true
!cond1: false
!cond2: true

Explanation:

1. In LogicalOperatorsDemo, we declare two Boolean variables cond1 and cond2, where cond1 is true and cond2 is false.

2. We then perform logical operations using && (AND), || (OR), and ! (NOT) operators. For example, cond1 && cond2 evaluates if both cond1 and cond2 are true, which in this case is false.

3. The || operator checks if at least one of cond1 or cond2 is true. Here, cond1 is true, so the whole expression evaluates to true.

4. The ! operator negates the Boolean value, so !cond1 returns false, and !cond2 returns true.

5. The output clearly shows each operation's result, which corresponds to the basic rules of logical operations in Boolean algebra.


Comments