学习链接:https://www.bilibili.com/video/BV1Xh411S7bP?p=141&spm_id_from=pageDriver


1 协变和逆变

  1. 协变:Son是Father的子类,则MyList[Son]作为MyList[Father]的子类

class MyList[+T]{}

  1. 逆变:Son是Father的子类,则MyList[Son]作为MyList[Father]的父类

class MyList[-T]{}

  1. 不变:Son是Father的子类,则MyList[Father]与MyList[Son]无父子关系

class MyList[T]{}

  1. object Test03_Generics {
  2. def main(args: Array[String]): Unit = {
  3. // 1. 协变和逆变
  4. val child: Parent = new Child
  5. val childList: MyCollection[Parent] = new MyCollection[Child]
  6. val childList1: MyCollection1[SubChild] = new MyCollection1[Child]
  7. }
  8. }
  9. // 定义继承关系
  10. class Parent {}
  11. class Child extends Parent {}
  12. class SubChild extends Child {}
  13. // 定义带泛型的集合类型
  14. class MyCollection[+E] {
  15. }
  16. class MyCollection1[-E] {
  17. }

2 泛型上下限

Class PersonList[T<:Person]{} // 泛型上限
Class PersonList[T>:Person]{} // 泛型下限
泛型的上下限的作用是对传入的泛型进行限定

object Test03_Generics {
  def main(args: Array[String]): Unit = {
    // 2. 测试上下限
    def test[A <: Child](a: A): Unit = {
      println(a.getClass.getName)
    }

//    test[Parent](new Child) // error 上限是Child,Parent不行
    test[Child](new Child) // chapter09.Child
    test[SubChild](new SubChild) // chapter09.SubChild
  }
}

// 定义继承关系
class Parent {}

class Child extends Parent {}

class SubChild extends Child {}

3 上下文限定

将泛型和隐式转换结合
def fA : B = println(a) //等同于 def fA(implicit arg:B[A])=println(a)