Sunday, 17 August 2014

Scala Note 7: Scala's == differs from Java's


Unlike Java, you compare the equality of two objects with == in Scala. In Java, the == operator compares “reference equality,” but in Scala, == is a method you use on each class to compare the equality of two instances, calling your equals method under the covers.

In Java, you can use == to compare both primitive and reference types.
On primitive types, Java's == compares value equality, as in Scala.
On reference types, however, Java's == compares 'reference equality',
which means the two variables point to the same object on the JVM's heap.

For example,

val x = "abcd".substring(2)
val y = "abcd".substring(2)
x == y
In java, returns false, x.equals(y) returns true.

but in scala returns true, x eq y, return false

Scala provides a facility for comparing reference equality, as well, under the same 'eq or ne'

No comments:

Post a Comment