package com.liao.day05
class CmpInt(a:Int,b:Int){
def bigger()={
if (a>b) a
else b
}
}
/*
* 上界(Upper Bonds):
* <:
* 相当于这个T是Comparable的子类
*/
class CmpComm1[T <: Comparable[T]](o1:T,o2:T){
def bigger()={
if (o1.compareTo(o2)>0) o1
else o2
}
}
/*
*视图界定
* <%
*/
class CmpComm2[T <% Comparable[T]](o1:T,o2:T){//T需要的是Comparable的子类
def bigger()={
if (o1.compareTo(o2)>0) o1
else o2
}
}
/**
*
* Ordered使用
*/
class CmpComm3[T <% Ordered[T]](o1:T,o2:T){//T需要的是Comparable的子类
def bigger()={
if (o1>o2) o1
else o2
}
}
/*学生类定义*/
class Student1(val name:String,val age:Int){
override def toString: String = this.name+"\t"+this.age
}
class Student2(val name:String,val age:Int) extends Ordered[Student2]{
override def compare(that: Student2): Int = this.age-that.age
override def toString: String = this.name+"\t"+this.age
}
//比较器编写
/**
*T:Ordering上下文界定
*/
class CmpComm4[T : Ordering](o1:T,o2:T){//T需要的是Comparable的子类
def bigger()={
//定义一个隐式转换比较类型
val cmptor=implicitly[Ordering[T]]
if(cmptor.compare(o1,o2)>0) o1 else o2
}
}
class CmpComm5[T : Ordering](o1:T,o2:T)(implicit cmptor:Ordering[T]){
def bigger()={
if(cmptor.compare(o1,o2)>0) o1 else o2
}
}
object ScalaUpperLowerBounds {
def main(args: Array[String]): Unit = {
val cmp1=new CmpInt(4,9)//scala自动帮我们做了下面的操作
val cmp2=new CmpInt(Integer.valueOf(4),Integer.valueOf(9))
println(cmp1.bigger())
val long1=new CmpComm1[java.lang.Long](3L,8L)//java的long才是实现了Comparable接口
println(long1.bigger())
val long2=new CmpComm2[Long](9L,11L)//这个视图界定可以有自动转换
println(long2.bigger())//这里不用显式的指定是Java的Long类型
val long3=new CmpComm3(3.14,4.999)
println(long3.bigger())//会自动转可比较类型
}
val studentA=new Student1("zhang",19)
val studentB=new Student1("li",22)
//隐式转换将一个普通的Student类转为---->Ordered[Student]可比较的类
implicit def student2OrderingStudent(student: Student1)=new Ordered[Student1]{
override def compare(that: Student1): Int = student.age-that.age
}
//直接比较不知道会比较什么,需要编写一个比较器
val studentCmp1=new CmpComm4(studentA,studentB)//把student转换成Ordering的Student类
println("================================"+studentCmp1.bigger()+"=====================================")
val studentC=new Student1("liao",18)
val studentD=new Student1("wang",50)
val studentCmp2=new CmpComm5(studentC,studentD)
println("================================"+studentCmp2.bigger()+"=====================================")
}