加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scalar中的基于Ordered和Ordering两种比较器

发布时间:2020-12-16 09:03:39 所属栏目:安全 来源:网络整理
导读:1Ordered 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($na

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("张三",new PPA("Ahan1",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
    }
  }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读