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:

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:

Comparison Operators with Booleans

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

Comparing Characters and Strings

In Scala, comparing characters (Char) works similarly to comparing numbers. The character that comes first alphabetically is "less than" the one that follows. Note, however, that Scala considers capital letters as "less than" lowercase letters because of their arrangement in the Unicode system. For strings (String), we use the == operator, which performs a case-sensitive comparison. Additionally, the operators >, <, >=, and <= are used to make comparisons in lexicographic order. Let's try comparing the characters 'a' and 'b', as well as the strings "alpha" and "beta":

Note for Java developers: In Scala, the == operator performs a value-based comparison for strings, similar to Java's String.equals method. This means you don't need to use equals explicitly for checking string equality, reducing the risk of mistakenly checking reference equality as often seen with the == operator in Java.

Lesson Summary and Upcoming Practice

Excellent! Today, you've learned how to apply comparison operators to fundamental data types in Scala using various examples. Stay tuned for hands-on exercises to consolidate the knowledge you've gained today. Let's continue our journey into this intriguing coding universe!

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