Scala - Relational Operators



Scala relational operators are used to compare values between operands (variables, constants, expressions) and return a Boolean value (true or false) based on the comparison. These operators are used in decisions and controlling program flow within conditional statements (if-else, switch, etc.).

The following relational operators are supported by Scala language. For example, let us assume variable A holds 10 and variable B holds 20, then −

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Example of Relational Operator

Consider the following example program to understand all the relational operators available in Scala programming language −

object Demo {
   def main(args: Array[String]) {
      var a = 10;
      var b = 20;
      
      println("a == b = " + (a == b) );
      println("a != b = " + (a != b) );
      println("a > b = " + (a > b) );
      println("a < b = " + (a < b) );
      println("b >= a = " + (b >= a) );
      println("b <= a = " + (b <= a) );
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

Relational operators can be used with various data types in Scala, like numbers, strings, characters, etc. You compare based on the lexicographical order (dictionary order) of the characters in the strings. You can chain multiple relational operators together using logical operators (&&, ||) for comparisons.

Advertisements