When desiging any kind of expression DSL, there is a need to create an expression for equality.
Please consider:
trait Expr[T] {
def same(other :Expr[T]) :Expr[T] = Eq(this, other)
}
case class Literal[T](value :T) extends Expr[T]
case class Eq[T](left :Expr[T], right :Expr[T]) extends Expr[Boolean]
The human mind being what it is, one naturally tends to use ==
to create such comparisons, leading to code like
e1 == e2
instead of
e1 same e2
Scala allows to define a method ==
which will be used instead of equals
, if present, and there is no technical reason why it couldn’t be used for the above purpose - equals
can be always invoked explicitly. This is the more desirable because other standard operators - <, <=, &&, ||
, etc. do not introduce ambiguity and are regularly used in this manner. There is even a precedent insizeIs
in the standard collection library already. The downside of course, is that someone wanting to really invoke equals
, will often write ==
for the same reasons, even if aware about these shenningans.
This isn’t a huge problem either way: one use case expects Boolean
as the return type, the other Expr[Boolean]
, so as long as there is no implicit conversion Boolean => Expr[Boolean]
, both kinds of mistakes will almost certainly be caught by the compiler. It is still a minor nuiscance however, and because I personally lean too much towards ‘magic’, I wanted to probe if hijacking ==
for this purpose would make people angry, because ultimately what matters is minimizing programmers’ annoyance.
To champion this idea a bit further, one can both have the cake and eat it, so to speak:
trait Expr[T] {
def ==(other :Expr[T]) = Eq(this, other)
}
case class Eq[T](left :Expr[T], right :Expr[T]) extends Expr[Boolean]
implicit def unliftEquality[T](e :Eq[T]) :Boolean = e.left == e.right
In the above case, ==
will work both as regular equality and meta equality, depending on the context,
and I can’t see it introducing tricky bugs. However, I know some people who would vehemently oppose such a solution on principle, so I’d like to poll how ‘the community’ feels about the idea.