scala 泛型类型

使用泛型类,通常是需要对类中的某些成员,比如某些field和method中的参数或变量,进行统一的类型限制,这样可以保证程序更好的健壮性和稳定性。

泛型类

class Student[T] (var Id:T)
{
 def getId(stuid :T) ="学生的ID"+id+stuid

}
  var s=new Student[Int](23)

泛型函数

def getCard[T] (context:T){
  if(context.isInstanceOf[Int])
   "本ID是001"+context
   else if(context.isInstanceOf[String])
    "this card"+context
    else "card"+context     
}
 getCard[Int](233)

泛型类边界类

class Person(var name:String){
 
 def sayHello=println("hello,i'm"+name)
 def makeFriends(Person p){
   sayHello
   p.sayHello
 }
 class Party[ T<: Person](p1 T,p2 T){//下边界
     p1.makeFriends(p2)
  }
}
##--------------------------------------------------------------------------------------------------

class Person(val name:String)
class Student(val name:String) extends  Father(name:String)
def getDcard[R>:Student]( Person p){
 if(person.getClass==class(P) )println("1234567890")
 else if(person.getClass==class(Student) println(" good student")

}

View Bounds 除了上下边界以外,支持出父子关系以外的多种类型相互转换

 class Person(name:String){
 def sayHello=println("good meeting everyone")
  def mkfriends(p:Person{
    sayHello
    p.sayHello
  }
 }
class Student(name:String) extends Person(name)
class Dog(name:String){
 def sayHello=println("we are family")  
}
 implicit def dogtoPerson(dog:Object):Person=if(dog.isInstanceOf[Dog]){
 var _dog=dog.asInstanceOf(Dog)
   new Person(_dog.name)
} else Nil
class Party[T<%Person](t1  T,t2 T)

泛型数组 实例化一个泛型数组

  class Meat (val name:String)
 class Vegatable(name:String)
 def packageFood[T :Manifest](food:T*) {
 var foodpakage=new Array[T](food.length)
 for(i<-0 until food.length) foodPackage(i)=food(i) 
  foodpakage

}

 泛型数组Array[_]

你可能感兴趣的:(scala 泛型类型)