Kevin Meredith
Kevin Meredith

Reputation: 41909

== and eq Operators

scala> val x = "a"
x: String = a

scala> val y = "a"
y: String = a

As I understand, == will call equals (value equality).

scala> x == y
res18: Boolean = true

But, x eq y, unexpected to me, shows true. eq, as I understand, checks for object identity.

scala> x eq y
res19: Boolean = true

Is the Scala compiler smart enough to return the same (identity) String object? I believe the term is interning.

Or, is eq actually performing a value equality?

Upvotes: 3

Views: 5396

Answers (2)

Akos Krivachy
Akos Krivachy

Reputation: 4966

Otávio is right, it should be the same as in Java.

To extend: the documentation of eq has quite a good explanation of what's expected of equality methods:

When overriding the equals or hashCode methods, it is important to ensure that their behavior is consistent with reference equality. Therefore, if two objects are references to each other (o1 eq o2), they should be equal to each other (o1 == o2) and they should hash to the same value (o1.hashCode == o2.hashCode).

Upvotes: 2

Otávio Décio
Otávio Décio

Reputation: 74270

Scala's String is actually Java.Lang.String, which in fact uses interning - see Scala Reference -

type String        = java.lang.String

Upvotes: 10

Related Questions