1.1. Testing String Equality

Problem

You want to compare two strings to see if they’re equal, i.e., whether they contain the same sequence of characters.

Solution

In Scala, you compare two String instances with the == operator. Given these strings:

scala> val s1 = "Hello"
s1: String = Hello

scala> val s2 = "Hello"
s2: String = Hello

scala> val s3 = "H" + "ello"
s3: String = Hello

You can test their equality like this:

scala> s1 == s2
res0: Boolean = true

scala> s1 == s3
res1: Boolean = true

A pleasant benefit of the == method is that it doesn’t throw a NullPointerException on a basic test if a String is null:

scala> val s4: String = null
s4: String = null

scala> s3 == s4
res2: Boolean = false

scala> s4 == s3
res3: Boolean = false

If you want to compare two strings in a case-insensitive manner, you can convert both strings to uppercase or lowercase and compare them with the == method:

scala> val s1 = "Hello"
s1: String = Hello

scala> val s2 = "hello"
s2: String = hello

scala> s1.toUpperCase == s2.toUpperCase
res0: Boolean = true

However, be aware that calling a method on a null string can throw a NullPointerException:

scala> val s1: String = null
s1: String = null

scala> val s2: String = null
s2: String = null

scala> s1.toUpperCase == s2.toUpperCase
java.lang.NullPointerException  // more output here ...

To compare two strings while ignoring their case, you can also fall back and use the equalsIgnoreCase of the Java String class:

scala> val a = "Marisa"
a: String = Marisa

scala> val b = "marisa"
b: String = marisa

scala> a.equalsIgnoreCase(b)
res0: Boolean = true

Discussion

In Scala, you test object equality with the == method. This is different than Java, where you use the equals method to compare two objects.

In Scala, the == method defined in the AnyRef class first checks for null values, and then calls the equals method on the first object (i.e., this) to see if the two objects are equal. As a result, you don’t have to check for null values when comparing strings.

Note

In idiomatic Scala, you never use null values. The discussion in this recipe is intended to help you understand how == works if you encounter a null value, presumably from working with a Java library, or some other library where null values were used.

If you’re coming from a language like Java, any time you feel like using a null, use an Option instead. (I find it helpful to imagine that Scala doesn’t even have a null keyword.) See Recipe 20.6, for more information and examples.

For more information on defining equals methods, see Recipe 4.15.

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.