Mandroid
Mandroid

Reputation: 7504

No equals in Ordered trait in Scala

Ordered trait in Scala has various comparison methods like <,<=,>,>= etc. But there is no method available for equality. Is it a design issue?

Upvotes: 0

Views: 314

Answers (3)

pramesh
pramesh

Reputation: 1954

This was intentional while designing scala. Because of type erasure, Ordered is not able to detect the type of the object which is needed to compare the equality of objects to be compared

Upvotes: 0

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

Even if it's an issue, it's a minor one. You can always just import math.Ordering, and there will be an automatic implicit conversion from Ordered to Ops, which provides an equiv method.

Simple example, an implementation of a method e that checks whether two elements are equivalent w.r.t. the canonical ordering:

import scala.math.Ordering

/** Checks whether `a` is equivalent to `b` w.r.t. 
  * the canonical ordering. */
def e[A <: Ordered[A]](a: A, b: A): Boolean = {
  val ord = implicitly[Ordering[A]]
  import ord._

  a equiv b
}

Since the equiv method is not provided after so many years, it seems that simply not enough people care about this issue. It just doesn't happen very often that a equiv b but a != b.

Upvotes: 1

Antot
Antot

Reputation: 3964

This is certainly not a design issue.

If you check the source code for Ordered trait, the implementations of all symbolic functions <, <=, > and >= are shortcuts to compareTo, which adheres to the Java convention for Comparable interface.

To check equality from the "ordering" point of view, you can use expressions like compareTo(arg) == 0 or compare(arg) == 0.

I suppose that there is no symbolic shortcut for such checks in order to avoid confusions with objects and references equality (equals() and == from Any). Moreover, def == is final in order to forbid it to be overriden.

Upvotes: 1

Related Questions