简体   繁体   中英

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?

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.

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 wrt 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM