scala泛型

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<two) one else two
}

//上下文界定
class P[T : Ordering](val one:T,val two:T){
  def smaller(implicit ord: Ordering[T])=
    if(ord.compare(one, two)<0) one else two
}

//Manifest上下文界定
class ManfiestTest{
  def makePair[T : Manifest](one:T,two :T){
    val r=new Array[T](2)
    r(0)=one
    r(1)=two
  }
}

//多重界定,其实就是限定类型范围
class A[T <:Comparable[T] with Serializable with Cloneable]

class B[T <% Comparable[T] <% String]

class C[T : Ordering : Manifest]

class D[T >: 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的要复杂点

 

posted @ 2016-12-09 16:13  全力以赴001  阅读(969)  评论(0编辑  收藏  举报