Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use '==' instead of equals for string comparison in Scala

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?

like image 765
Core_Dumped Avatar asked Jul 21 '14 08:07

Core_Dumped


People also ask

Can you compare strings 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.

Can we use == for string comparison?

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.

Can you use .equals for string?

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.

Can you use comparison operators on strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.


1 Answers

In Scala, == is equivalent to equals except that it handles null so no NullPointerException is thrown.

If you want reference equality, use eq.

like image 57
Jean Logeart Avatar answered Oct 20 '22 00:10

Jean Logeart