package com.ming.test/** * scala泛型 * 类型参数测试 */object TypeParamsTest { //泛型函数 def getMiddle[T](a:Array[T])=a(a.length/2) //类型通配符 def process1(people:java.util.List[_<:Student])={} def main(args: Array[String]): Unit = { val p=new Pair(42,"String") val p2=new Pair[Any,Any](42,"ddd") val c=new Compare("A","B"); println(c.smaller) } }//定义一个类型参数的类class Pair[T,M](var one:T,var two :M)//T必须是Comparable[T]的子类型.class Compare[T<:Comparable[T]](val one:T,val two : T){ def smaller=if(one.compareTo(two)<0) one else two}//视图界定/** * <%关系意味这T可以被隐式转换成Comparable[T],还可以用Ordered特质 */class PairT[T <% Comparable[T]]class PairTT[T <% Ordered[T]](val one:T,val two:T){ def smaller=if(one: String <:String]abstract class List[+T]{ def isEmpty :Boolean def head :T def tail: List[T]}object Empty extends List[Nothing]{ def isEmpty=true def head=throw new UnsupportedOperationException def tail=throw new UnsupportedOperationException}class Student{}
scala的泛型比java的要复杂点