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



我正在使用另一个关闭API的Location对象工作,并且它已经具有返回StringtoString()方法。我只想要一个implicit函数,可以通过比较其toString()值来比较两个Location实例。所以我将能够去

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

考虑将隐式转换为类型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")

只是...

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

相关内容

  • 没有找到相关文章

最新更新