0

我正在使用Location来自另一个封闭 API 的对象,它已经有一个toString()返回String. 我只想要一个可以通过比较它们的值implicit来比较两个Location实例的toString()函数。所以我可以去

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

2 回答 2

1

考虑提供对 type 实例的隐式转换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需要它作为隐式参数。实现将比 for 更短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")
于 2018-02-08T07:33:06.990 回答
0

只是...

implicit class LocationUtil(l: Location) {
  def > (l2: Location): Boolean = if (l.toString() >= l2.toString()) true else false
}
于 2018-02-08T06:22:30.303 回答