I know that the == method in Scala has the same semantics of the equals method in Java. However, I would like to understand when applied to instances of recursive structures.
For instance, consider a bunch of expressions:
abstract class Exp
abstract class BinaryExp(l:Exp, r:Exp) extends Exp
case class Plus(l:Exp, r:Exp) extends BinaryExp(l,r)
case class Minus(l:Exp, r:Exp) extends BinaryExp(l,r)
case class Mult(l:Exp, r:Exp) extends BinaryExp(l,r)
case class Div(l:Exp, r:Exp) extends BinaryExp(l,r)
case class Num(v:Int) extends Exp
Then, when I have two instances of a BinaryExp, say obj1 and obj2, does obj1 == obj2 result in a deep (recursive) equality test? That is, is it guaranteed that if obj1 == obj2 holds, then obj1 and obj2 represent the same exact expression trees?
Note that in all classes, I am relying on the default implementation of == (it is not overridden anywhere).
This is easy to test yourself:
The fact that these give the correct answers shows that the equality check is checking for “deep” equality of subexpressions.
Furthermore, you can see in the documentation that:
“Structural equality” is the kind of deep equality checking that you are wondering about.
Finally, if you really want to see what’s happening beyond on the syntactic sugar, you can use the option
-xPrint:typerwhen you runscalacor start the REPL. If you use that option with the REPL and then declare the classPlus, here’s what you get (shortened):So, buried in the first
caseyou’ll see thatPlus.equalsis callingif l$1.==(l).&&(r$1.==(r))in order to check equality. In other words, the generated equality method of a case class calls==on its subexpressions to check their equality.