How to compare two strings in scala?

Rosy b picture Rosy b · Oct 10, 2014 · Viewed 29.1k times · Source

I want to compare two strings in scala. for example,

My Strings are:

scala java
scala java c++
scala c++

I want to compare the string

" scala c++" with each strings

Results should be,

scala c++ = scala java   // false
scala c++ = scala java c++  // false
scala c++ = scala c++   // true

Answer

oluies picture oluies · Oct 10, 2014

In Scala you can use == for equality

scala> "scala c++" == "scala java"
res0: Boolean = false
scala> "scala c++" == "scala java c++"
res1: Boolean = false
scala> "scala c++" == "scala c++"
res2: Boolean = true

The == method is defined in the AnyRef class. Since the methods first checks for null values, and then calls the equals method on the first object to see if the two objects are equals you dont have to do a special null check;

"test" == null
res0: Boolean = false

See the Scala getting started guide and strings

From "An Overview of the Scala Programming Language Second Edition";

"The equality operation == between values is designed to be transparent with respect to the type's representation. For value types, it is the natural (numeric or boolean) equality. For reference types, == is treated as an alias of the equals method from java.lang.Object. That method is originally defined as reference equality, but is meant to be overridden in subclasses to implement the natural notion of equality for these subclasses. For instance, the boxed versions of value types would implement an equals method which compares the boxed values. By contrast, in Java, == always means reference equality on reference types. While this is a bit more efficient to implement, it also introduces a serious coherence problem because boxed versions of equal values might no longer be equal with respect to ==. Some situations require reference equality instead of user-dened equality. An example is hash-consing, where eciency is paramount. For these cases, class AnyRef defines an additional eq method, which cannot be overridden, and is implemented as reference equality (i.e., it behaves like == in Java for reference types)."