Introduction and Lesson Overview

Greetings! Today, we're learning about comparison operators in Scala. This fundamental concept is central to decision-making in coding. As part of our lesson, we will delve into a range of examples involving various data types to comprehend their usage. So, let's dive into the discovery!

Understanding Comparison Operators

Suppose you attend a daily contest in which we gauge who's taller or faster. If we replace these parameters with "greater," "lesser," "equal," or "not equal," we will have the comparison operators! Scala employs several principal ones:

  1. Equal to (==)
  2. Not equal to (!=)
  3. Greater than (>)
  4. Less than (<)
  5. Greater than or equal to (>=)
  6. Less than or equal to (<=)

Let's examine these operators using simple examples:

@main def run: Unit = 
  val num1 = 5
  val num2 = 10

  println(num1 == num2)  // prints: false, as 5 is not equal to 10
  println(num1 != num2)  // prints: true, as 5 is not equal to 10
  println(num1 > num2)   // prints: false, as 5 is not greater than 10
  println(num1 < num2)   // prints: true, as 5 is less than 10
  println(num1 >= num2)  // prints: false, as 5 is not greater than or equal to 10
  println(num1 <= num2)  // prints: true, as 5 is less than or equal to 10

These comparisons of 5 and 10 using the operators yield boolean values (true or false).

Applying Comparison Operators on Numbers

Imagine two siblings: Harry, aged 12, and Ron, aged 14. We can compare their ages using comparison operators:

@main def run: Unit = 
  val ageHarry = 12
  val ageRon = 14

  println(ageHarry == ageRon)  // prints: false, as Harry and Ron are of different ages
  println(ageHarry != ageRon)  // prints: true, as above
  println(ageHarry > ageRon)   // prints: false, as Harry is younger than Ron
  println(ageHarry < ageRon)   // prints: true, as Harry is younger than Ron
  println(ageHarry >= ageRon)  // prints: false, as Harry is younger or not as old as Ron
  println(ageHarry <= ageRon)  // prints: true, as Harry is younger or as old as Ron (in this case, younger)
Comparison Operators with Booleans

Now, let's compare Boolean variables. Please note that we use the operators == and != in this case:

@main def run: Unit = 
  val isMorning = true
  val isAfternoon = false

  println(isMorning == isAfternoon)  // prints: false, as true is not the same as false
  println(isMorning != isAfternoon)  // prints: true, as true is not equal to false
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal