我正在处理来自其他已关闭API的Location
对象,并且它已经有一个返回toString()
的{{1}}方法。我只想要一个String
函数,可以比较两个implicit
实例,比较它们的Location
值。所以我可以去
toString()
答案 0 :(得分:1)
考虑提供对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")
答案 1 :(得分:0)
它只是......
implicit class LocationUtil(l: Location) {
def > (l2: Location): Boolean = if (l.toString() >= l2.toString()) true else false
}