Scala String FAQ: How do you compare string equality in Scala?
In Scala you compare two Strings with the
== operator. This is different than Java, where you compare two Strings with the
For example, 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
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
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
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.
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, orsome 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
Optioninstead. I find it helpful to imagine that Scala doesn’t even have a