祝各位道友念头通达
GitHub Gitee 语雀 打赏

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

}

 

posted @ 2018-11-26 15:18  韩若明瞳  阅读(276)  评论(0编辑  收藏  举报