10

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?

Core_Dumped
  • 4,577
  • 11
  • 47
  • 71
  • 4
    Scala is not Java, even though it is hosted by the JVM. More specifically, what's safe in Scala is not safe in Java. – Elliott Frisch Jul 21 '14 at 08:46
  • 3
    [Whats the difference between == and .equals in Scala?](http://stackoverflow.com/questions/7681161/whats-the-difference-between-and-equals-in-scala) – Govind Singh Jul 21 '14 at 08:55
  • Scala aimed to iron out many of the illogical annoyances in Java. One of these were `==` vs `.equals`, it's not obvious to newcomers when to use which, so instead they decided you'd just use `==` for everything, which makes a lot more sense from a usability standpoint – Electric Coffee Jul 21 '14 at 09:45
  • 1
    Where did you get the idea that `==` is reference equality? – Jörg W Mittag Jul 21 '14 at 11:09
  • @JörgWMittag http://stackoverflow.com/questions/3689952/using-instead-of-equals-for-java-strings – Core_Dumped Jul 21 '14 at 11:12
  • 1
    That question is for a completely different programming language that has absolutely nothing whatsoever to do with [tag:scala]. – Jörg W Mittag Jul 21 '14 at 11:15
  • @JörgWMittag Okay, I understand the fact that it is a different language than Scala but stating it to have "absolutely nothing whatsoever to do with Scala" is a little far-fetched. Don't you think? – Core_Dumped Jul 21 '14 at 11:19

1 Answers1

24

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

If you want reference equality, use eq.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • 4
    There are other minor differences between `==` and `equals`, e.g. `==` is aware of numeric equivalence: `1==1L` but `!1.equals(1L)`. In general, `==` is the reasonable operator to use unless there is an explicit reason not to do so. – blintend Jul 21 '14 at 09:18
  • True that! ``==`` is to be preferred in Scala. – Jean Logeart Jul 21 '14 at 09:18