泛型类
泛型类:在Scala的类中定义参数类型
泛型类的应用场景:对类中的某些成员(field和method中的参数或变量)进行统一的类型限制,从而确保程序的健壮性和稳定性
class MyCollection[T]{private val list =new ListBuffer[T]()//增加一个元素def add(el:T): Unit ={list.append(el)}//删除def remove(el:T): Unit ={list.-=(el)}override def toString = s"MyCollection($list)"
}
object MyCollection{def main(args: Array[String]): Unit = {//定义前声明泛型类型val c = new MyCollection[Int]()c.add(2:Int)println(c)c.remove(2:Int)println(c)}
}
泛型函数
泛型函数:类似于泛型类,在声明函数时指定泛型类型,然后在函数体中,就可以使用这种泛型类型来声明变量或作为函数的返回值类型,从而强制性对变量或返回值进行类型限制。
class School{}
class Student(name:String) extends School{}
class Teacher(name:String) extends School{}
class Whh(name:String){}
object FunDemo {def main(args: Array[String]): Unit = {val student = new Student("小李")val teacher = new Teacher("jack")val w = new Whh(" www")door[School](student)door[School](teacher)//door[School](w)}def door[T](per:T): Unit ={if(per.getClass == classOf[Student]){println("student 允许进入")}else if(per.getClass == classOf[Teacher]){println("teacher 允许进入")}else{println("不允许进入。。。")}}
}
上边界
Scala中的上边界定义语法:T <: 父类
package cn.alibaba.scala.genericity
class Shool{var name:String = _def chat(s:Shool): Unit ={println(this.name+"和"+s.name+"一起聊天")}
}
class Student(stuName:String) extends Shool{this.name = stuName
}
class Teacher(teaName:String) extends Shool{this.name = teaName
}
class Stranger(name: String){}
//定义泛型边界 最大 为Shool
class Party[T <: Shool](p1:T,p2:T){def eat = p1.chat(p2)
}
object Party {def main(args: Array[String]): Unit = {val stu = new Student("鲁鲁")val tea = new Teacher("卡卡")val str = new Stranger("路人")val par = new Party(stu,tea)par.eat}
}
下边界
Scala中的上边界定义语法:T >: 子类
class GranderFather
class Father extends GranderFather
class Son extends Father
class Tongxue
object Card{
//最小边界为father类def getIDCard[T >: Father](person:T): Unit ={println("OK,交给你了")}def main(args: Array[String]): Unit = {getIDCard[GranderFather](new Father)getIDCard[GranderFather](new GranderFather)/*** 下面代码回报错 边界Father*/getIDCard[Son](new Son)//getIDCard[GranderFather](new Tongxue)//报错,所以注释}
}
认真看下边界这段代码就会体会到泛型边界的含义以及控制范围!