- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
AnyRef: Object Equality Question
Wed, 2010-03-17, 08:33
Hi there,
can someone explain why the results are different?
val x = new String("abc")
val y = new String("abc")
x == y
true
x eq y
false
Now try this:
val x1 = "abc"
val y1 = "abc"
x1 == y1
true
x1 eq y2
true
I suppose this is correct behavior, however I would have expected same
results. Please enlighten me.
Cheers
Wed, 2010-03-17, 09:07
#2
Re: AnyRef: Object Equality Question
> val x = new String("abc")
> val y = new String("abc")
In this case, you create two distinct String objects, both of which have the same data.
> val x1 = "abc"
> val y1 = "abc"
In this case, you reference the same String object twice. The environment was kind enough to resolve both references to the same string to the same object, so as not to waste your memory. Better not to rely on this behavior though, as it depends on where those string references appear (I'm not actually sure when, precisely, two constant strings resolve to the same object and when they do not). See also java.lang.String#intern().
Niko
Wed, 2010-03-17, 09:07
#3
Re: AnyRef: Object Equality Question
On Mar 17, 2010, at 8:54 AM, Niko Matsakis wrote:
> Better not to rely on this behavior though, as it depends on where those string references appear (I'm not actually sure when, precisely, two constant strings resolve to the same object and when they do not). See also java.lang.String#intern().
Reading the docs for intern(), I see that "All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification". So I guess that you can rely on it, even across classes etc. Nonetheless I think it's better style to define a field and compare that for equality (actually, I'd just use == in the first place: it's equally fast it both strings are interned, and hence pointer equal).
regards,
Niko
Hi,
== in Scala is similar to 'equals' in Java
eq in Scala is what '==' is in Java (reference equality)
I think, that your results are the same as in Java. x and y reference
different objects (you made sure by using 'new'), so x eq y is false.
String constants, however, are different. They come from the constant
pool which is sort of a cache for constants in the JVM.
Johannes
On Wed, Mar 17, 2010 at 8:33 AM, learning scala wrote:
>
> Hi there,
>
> can someone explain why the results are different?
>
> val x = new String("abc")
> val y = new String("abc")
>
> x == y
> true
>
> x eq y
> false
>
> Now try this:
>
> val x1 = "abc"
> val y1 = "abc"
>
> x1 == y1
> true
>
> x1 eq y2
> true
>
> I suppose this is correct behavior, however I would have expected same
> results. Please enlighten me.
>
> Cheers
> --
> View this message in context: http://old.nabble.com/AnyRef%3A-Object-Equality-Question-tp27928211p2792...
> Sent from the Scala - User mailing list archive at Nabble.com.
>
>