🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Comparison Operators

Comparison operators compare two values and give a Boolean result. The result is either true or false.

== and != test sameness

Each comparison prints true or false. Equal values give true for == and false for !=.

@main def main(): Unit =
  println(5 == 5)
  println(5 == 8)
  println(5 != 8)

<, >, <= and >= test order

These signs compare size from left to right. A value counts as >= and <= itself.

@main def main(): Unit =
  println(3 < 5)
  println(9 <= 9)
  println(4 > 10)
  println(7 >= 7)

== compares string text

Two strings with the same letters compare equal. Different text gives false.

@main def main(): Unit =
  val city = "Oslo"
  println(city == "Oslo")
  println(city == "Paris")
  println(city != "Paris")

Example

@main def main(): Unit =
  val age = 18
  val name = "Mia"
  println(age >= 18)
  println(age < 21)
  println(name == "Mia")
  println(name != "Mia")

Key points

  • Equal: == checks whether two values are the same.
  • Not equal: != checks whether two values are different.
  • Less than: < checks whether the left value is smaller.
  • Greater than: > checks whether the left value is bigger.
  • At least: >= checks whether the left value is bigger or equal.
  • At most: <= checks whether the left value is smaller or equal.
  • Strings: == compares the text inside two strings, letter by letter.

In this example, age is 18, so age >= 18 is true and age < 21 is also true. The name holds the text Mia, so name == "Mia" is true. That makes name != "Mia" false.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does println(7 <= 7) print?