How do you test reference equality in Scala?
val x = new Obj val y = x x.referenceEquals(y) // evaluates to true
== operator is used to check whether two variables reference objects with the same value.
But in Scala, == is testing for value equality. Let's understand with example. Example : Scala.
== is a final method, and calls . equals , which is not final. This is radically different than Java, where == is an operator rather than a method and strictly compares reference equality for objects.
Use the ReferenceEquals method to determine whether two references refer to the same object. The concept of reference equality applies only to reference types. Value type objects cannot have reference equality because when an instance of a value type is assigned to a variable, a copy of the value is made.
The function you are looking for is eq
, which is a member of AnyRef:
val x = new Obj val y = x x eq y // evaluates to true x ne y // evaluates to false
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