隐式函数,用于比较Scala中的两个封闭类

时间:2018-02-08 04:46:46

标签: scala functional-programming scala-2.10 implicits scala-implicits

我正在处理来自其他已关闭API的Location对象,并且它已经有一个返回toString()的{​​{1}}方法。我只想要一个String函数,可以比较两个implicit实例,比较它们的Location值。所以我可以去

toString()

2 个答案:

答案 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
}