在 Scala 中比较两个封闭 类 的隐式函数

implicit function that compares two closed classes in Scala

我正在使用来自另一个已关闭 API 的 Location 对象,它已经有一个 toString() 方法 returns 和 String。我只想要一个 implicit 函数,它可以通过比较两个 Location 实例的 toString() 值来比较它们。这样我就可以去

val L1 = new Location(**Parameters for Location**)
val L2 = new Location(**Parameters for Location**) 
if (L2 > L1) { **do something** } 

只是...

implicit class LocationUtil(l: Location) {
  def > (l2: Location): Boolean = if (l.toString() >= l2.toString()) true else false
}

考虑向 Ordered:

类型的实例提供隐式转换
case class Location(x: Int, y: Int, s: String)

import scala.math.Ordered

implicit class LocationOrdered(val loc: Location) 
extends Ordered[LocationOrdered] {
  def compare(other: LocationOrdered): Int = {
    this.loc.toString.compare(other.loc.toString)
  }
}

val a = Location(123, 456, "foo")
val b = Location(456, 789, "bar")

println("a = " + a + " b = " + b)

if (a > b) println("a > b") else println("! a > b")
if (a >= b) println("a >= b") else println("! a >= b")
if (a <= b) println("a <= b") else println("! a <= b")
if (a < b) println("a < b") else println("! a < b")

这样,你自动免费获得所有其他比较方法<=<>=>


正如@AlexeyRomanov 指出的那样,通常最好在范围内使用隐式 Ordering ,因为例如 List.sort 需要它作为隐式参数。实现会比 Ordered:

更短
import scala.math.Ordering
import scala.math.Ordering._

implicit object LocationOrdering extends Ordering[Location] {
  def compare(a: Location, b: Location) = a.toString.compare(b.toString)
}

这样我们就可以像这样比较 Location 值:

val locationOrdering = implicitly[Ordering[Location]]
import locationOrdering._
val a = Location(123, 456, "foo")
val b = Location(456, 789, "bar")

if (a > b) println("a > b") else println("! a > b")