有没有办法为两个不同的类定义相同的隐式排序?

我试图按照以下方式做一些事情,但它没有检测到排序。

abstract class Common
case class A extends Common
case class B extends Common

implicit val KeyOrdering = new Ordering[Common] {
    override def compare(x: Common, y: Common): Int = {
      x.toString.compareTo(y.toString)
   }
}

最佳答案

正如@ntn 所指出的,您的列表的推断类型 - 其两个元素的最小上限 - 是 Product with Serializable with Common 。由于 scala.Ordering 在其类型参数上不是逆变的,隐式解析失败,因为它不保存 Ordering[Common] <: Ordering[Product with Serializable with Common]

您可以通过编写隐式排序来解决此问题,以便它始终具有所考虑的隐式参数的确切类型:

abstract class Common
case class A() extends Common
case class B() extends Common

object Common {
  implicit def ordering[A <: Common]: Ordering[A] = new Ordering[A] {
    override def compare(x: A, y: A): Int = {
      x.toString.compareTo(y.toString)
    }
  }
}

或者为了简洁:
object Common {
  implicit def ordering[A <: Common]: Ordering[A] = Ordering.by(_.toString)
}

关于Scala 隐式排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25733902/

10-12 22:51