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 == s2res0: Boolean = true scala>s1 == s3res1: 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 = nulls4: String = null scala>s3 == s4res2: Boolean = false scala>s4 == s3res3: 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.toUpperCaseres0: Boolean = true
However, be aware that calling a method on a
null string can throw a NullPointerException:
scala>val s1: String = nulls1: String = null scala>val s2: String = nulls2: String = null scala>s1.toUpperCase == s2.toUpperCasejava.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" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access