1、Upper Bounds
//upper bounds R >: Tclass Pair1[T](val first:T,val second:T){ def replaceFirst[R >: T](newFirst:R)= new Pair1(newFirst,second)}class Book(val name:String)class Ebook(name:String) extends Book(name)class Pbook(name:String) extends Book(name)object GenericDemo extends App{ val first = new Ebook("hello") val second = new Pbook("paper book") val p1 = new Pair1(first,second) println(p1) val newFirst = new Book("generic") val p2 = p1.replaceFirst(newFirst) println(p2)}
2、Lower Bounds
//lower bounds T <: Mclass Pair[T <: Comparable[T]](val first:T,val second:T){ def smaller = { if(first.compareTo(second) < 0) first else second }}object GenericDemo extends App{ val p = new Pair("A","B") println(p.smaller)}
3、View Bounds
//view bounds,允许隐式转化,比如Int不支持Comparable但是RichInt支持class Pair3[T <% Comparable[T]](val first:T,val second:T){ def smaller = { if(first.compareTo(second) < 0) first else second }}object GenericDemo extends App{ val idemo = new Pair3(1,2) println(idemo.smaller)}
4、Context Bounds
// [T:M],T 隐式转换为 Mclass Pair[T : Ordering](val first : T, val second : T){ def smaller(implicit ord : Ordering[T]) = if(ord.compare(first,second) < 0) first else second}class Line(val len : Double){ override def toString() = "Length of line : " + len}trait LineOrdering extends Ordering[Line] { override def compare(x: Line, y: Line) = if (x.len < y.len) -1 else if (x.len == y.len) 0 else 1}object ContextBounds extends App{ implicit object Line extends LineOrdering val le1 = new Line(1.0) val le2 = new Line(2.0) val p = new Pair(le1,le2) println(s"smaller => ${p.smaller}")}