Why is it recommended to use ==
rather than .equals
for string comparison in Scala? There are a lot of questions in StackOverflow that do not recommend the use of reference equality for String comparison in Java but why is it advised to do the exact reverse in Scala?
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.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
In Scala, ==
is equivalent to equals
except that it handles null
so no NullPointerException
is thrown.
If you want reference equality, use eq
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With