Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference equality for java.lang.String in Scala

One would expect that even though strings are immutable, value-equality and reference-equality would not be the same for java.lang.String objects in Scala. This means that two string-holding vals should not be reference-equal even when their strings are identical. But here's what I get in a 2.9.1.final REPL:

scala> val s1 = "a"; val s2 = "a"
s1: java.lang.String = a
s2: java.lang.String = a

scala> s1 eq s2
res0: Boolean = true

Any idea why the result was not false? The same experiment with List("a") instead of "a" works as expected. The eq method is marked as final in AnyRef. Is there any compiler magic done specifically for String or java.lang.String?

like image 644
Oleg Mirzov Avatar asked Apr 09 '12 10:04

Oleg Mirzov


People also ask

What is the difference between equals () and == in Scala?

operators. The operator == is the same as equals method. It is also used to compare the equality of values. The operator == returns True if both the values being compared are the same, and returns False otherwise.

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.

Does Scala use ==?

Methods: While == is an operator in several languages, Scala reserved The == equality for the natural equality of every type. it's a method in Scala, defined as final in Any. value equality will be tested by this. Here, x == y is true if both x and y have the same value.

What does :+ mean in Scala?

On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.


2 Answers

Yes it's compiler magic. Specifically, it's called interning. Java does it as well, and it's simply for efficiency reasons, such as memory usage and allowing comparisons without comparing every character. Here's a Wikipedia article on it. You can also intern Strings manually with the intern() method.

like image 58
Luigi Plinge Avatar answered Oct 09 '22 11:10

Luigi Plinge


From the Java language specification:

A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

like image 23
fredoverflow Avatar answered Oct 09 '22 10:10

fredoverflow