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.
Here's a quick demonstration that shows this works. If you run the following Scala String tests in the Scala REPL or in your favorite IDE:
package tests
object StringEqualityTests {
def main(args: Array[String]) {
val s1 = "Hello"
val s2 = "Hello"
val s3 = "Goodbye"
val s4:String = null
val s5 = "H" + "ello"
if (s1 == s2) println("s1 == s2, good")
if (s1 == s3) println("s1 == s3, bad")
if (s1 == s4) println("s1 == s4, bad")
if (s1 == s5) println("s1 == s5, good")
}
}
you'll get the following output:
s1 == s2, good s1 == s5, good
If you review those tests, you'll see that this is correct.
I'll write more about how the Scala == operator (method, actually) works in the future, but for now just know that you can use == to compare two Strings in Scala.
This page is sponsored by Valley Programming - Boulder, Colorado Scala consultant
want to sponsor a page? learn more.
Post new comment