In Scala you compare Strings with '==', not 'equals'

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 equals method.

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 == 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.

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 Option instead. I find it helpful to imagine that Scala doesn’t even have a null keyword.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.