gpt4 book ai didi

Scala 隐式排序

转载 作者:行者123 更新时间:2023-12-04 02:45:35 25 4
gpt4 key购买 nike

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

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com