马老爷子真牛逼,泛型搞了这么多的上界、下界、ViewBound、ContextBound,开发学的不亦乐乎啊
需求仍然是选择girl.
步骤:
1、新建MyGirl类
class MyGirl(val name:String,val age:Int,val faceValue:Int){}
2、新建ContexBoundDemo
class ContextBoundDemo[T: Ordering] {//为啥这个地方Ordering后面又不加T了呢?真尼玛诡异 def selectGirl(g1: T, g2: T): T = { val ord: Ordering[T] = implicitly[Ordering[T]] if (ord.gt(g1, g2)) g1 else g2 }}
这个地方,我不太理解,为啥Ordering后面就不加T了,之前Ordered全加的,梁东老师讲的不是很透彻,只能靠我再去看书了。
3、新建一个隐式值
package testimplicitimport scalapackage.testfanxing.MyGirl/** * Created by Germmy on 2018/4/8. */object MyPreDef { implicit object OrderingGirl extends Ordering[MyGirl]{ override def compare(x: MyGirl, y: MyGirl): Int = { if(x.faceValue==y.faceValue){ y.age-x.age }else{ x.faceValue-y.faceValue } } }}
4、新建main
object ContextBoundDemo { def main(args: Array[String]) { import testimplicit.MyPreDef.OrderingGirl val cbd = new ContextBoundDemo[MyGirl] val g1=new MyGirl("daya",40,90) val g2=new MyGirl("erya",39,90) val res=cbd.selectGirl(g1,g2) println(res.name) }}