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 val
s 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
?
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.
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.
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.
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.
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.
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 methodString.intern
.
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