范型
2017-06-12 本文已影响0人
博瑜
<:上界 >:下界
class Pair[T<:Comparable[T]] { //上界,对传入类型进行约束
def bigger(first:T, second:T): T = {
if (first.compareTo(second) > 0) first else second
}
}
object Pair {
def main(args: Array[String]): Unit = {
val p = new Pair[Integer]
println(p.bigger(2,1))
}
}
<%视图定界 一定要传隐式转换函数 T隐式转换成order[T]
[T<%M]关系意味着T可以隐式转换成M[T], E.g [T<%Comparable[T]]
object MyPreDef {
implicit val girl2Ordered = (g:Girl) => new Ordered[Girl] {
//implicit def girl2Ordered(g:Girl) = new Ordered[Girl] {
override def compare(that: Girl): Int ={
g.faceValue - that.faceValue
}
}
// implicit val girl2Ordering = new Ordering[Girl] {
// override def compare(x: Girl, y: Girl): Int = {
// println("@@@")
// x.faceValue - y.faceValue
// }
// }
trait girl2Ordering extends Ordering[Girl] {
override def compare(x: Girl, y: Girl): Int = {
println("@@@")
x.faceValue - y.faceValue
}
}
implicit object Girl extends girl2Ordering
}
//视图界定 必须传入一个隐式转换函数
//class chooser[T <% Ordered[T]] {
// def choose(first:T, second:T): T = {
// if (first > second) first else second
// }
//}
上下文界定[T:M],要求必须存在一个类型为M[T]的隐式值
//上下文界定 必须传入一个隐式转换的值 Ordering 后面不用写T了
class chooser[T : Ordering] {
def choose(first:T, second:T): T = {
val ord = implicitly[Ordering[T]]
if (ord gt(first, second)) first else second
}
}
class Girl(val name:String, val faceValue:Int)
object chooser {
def main(args: Array[String]): Unit = {
import MyPreDef._
val g1 = new Girl("p", 90)
val g2 = new Girl("t", 100)
val c = new chooser[Girl]
println(c.choose(g1, g2).name)
}
}