scalar中的基于Ordered和Ordering两种比较器
1>Ordered
class PP(var name: String, var age: Int) extends Ordered[PP] { override def compare(that: PP) = if (this.age > that.age) -1 else if (this.age < that.age) 1 else this.name.compareTo(that.name); override def toString = s"PP($name, $age)" } mutable.SortedSet(new PP("张三", 12), new PP("Ahan1", 13), new PP("han1", 13)).foreach(print(_))
>Ordering(这里通过需要将写在伴生对象里,必须用参数接收,必须用implicit关键字修饰,也可采用第二种方法写)
class PPA(var name: String, var age: Int) { override def toString = s"PPA($name, $age)" } object PPA { implicit val obj1 = new Ordering[PPA] { override def compare(x: PPA, y: PPA): Int = { if (x.age < y.age) -1 else 1 } } } mutable.SortedSet(new PPA("张三", 12), new PPA("Ahan1", 13), new PPA("han1", 13)).foreach(print(_))
第二种方案:(同样在伴生对象里)
object PPA { implicit object obj extends Ordering[PPA] { override def compare(x: PPA, y: PPA): Int = { if (x.age < y.age) -1 else 1 } } }
本文来自博客园踩坑狭,作者:韩若明瞳,转载请注明原文链接:https://www.cnblogs.com/han-guang-xue/p/10020478.html