方法一:
使用隐式对象 implicit object 继承 Ordering[T]类,重写compare方法实现
代码语言:javascript复制// 随机定义一个方法
class XiaoHei(val name:String, val age:Int) {
// 重写toString方法
override def toString:String = s"name:${name}, age:${age}"
}
object Scala4 {
// 定义隐式对象
implicit object Order extends Ordering[XiaoHei]{
// 重写(自定义)compare方法
override def compare(x:XiaoHei, y:XiaoHei): Int = x.age -y.age
}
}
object OderingDemo {
// 定义比较方法
def choose(t1:XiaoHei, t2:XiaoHei): XiaoHei = {
// 引入隐式对象
import Scala4.Order
if (Ordering[XiaoHei].compare(t1, t2) > 0) t1 else t2
}
// 主方法
def main(args:Array[String]): Unit = {
val s1 = new XiaoHei("小黑",10)
val s2 = new XiaoHei("小白", age = 12)
println(choose(s1,s2))
}
}
运行结果
方法二:
定义Comparable的实现类,实现CompareTo方法;
再定义一个以Comparable为参数的泛型类,方法实现比较逻辑
代码语言:javascript复制// 定义泛型类,接受参数为Comparable的实现类
class ChooseClass[T <: Comparable[T]] {
// choose方法实现Comparable实现类的具体比较
def choose(t1:T, t2:T): T = {
if (t1.compareTo(t2) >0) t1 else t2
}
}
// 定义comparable的实现类,实现compareTo方法
class CompareClass(val name:String) extends Comparable[CompareClass] {
override def toString:String = this.name
override def compareTo(o: CompareClass): Int = this.name.compareTo(o.name)
}
// 测试类
object Test {
def main(args:Array[String]): Unit = {
val choose1 = new ChooseClass[Integer]
println(choose1.choose(100,200))
val choose2 = new ChooseClass[CompareClass]()
println(choose2.choose(new CompareClass("小黑"),new CompareClass("小白")))
}
}
运行结果