• 协变(Covariance)、逆变(Contravariance)与不变(Invariance)in Scala


    Scala 中的协变(Covariance)、逆变(Contravariance)与不变(Invariance)

    型变(VARIANCES)

    型变是复杂类型的子类型关系与其组件类型的子类型关系的相关性。

    Scala支持 泛型类 的类型参数的型变注释,允许它们是协变的,逆变的,或在没有使用注释的情况下是不变的。 在类型系统中使用型变允许我们在复杂类型之间建立直观的连接,而缺乏型变则会限制类抽象的重用性。

    class Foo[+A] // A covariant class
    class Bar[-A] // A contravariant class
    class Baz[A]  // An invariant class
    
    • 1
    • 2
    • 3

    协变

    1. 定义侧协变

    协变 如果 A 是 B 的子类型,那么 List[A] 就是 List[B] 的子类型

    使用注释 +A,可以使一个泛型类的类型参数 A 成为协变。 对于某些类 class List[+A],使 A 成为协变意味着对于两种类型 A 和 B,如果 A 是 B 的子类型,那么 List[A] 就是 List[B] 的子类型。 这允许我们使用泛型来创建非常有用和直观的子类型关系

    Scala 标准库有一个通用的不可变的类 sealed abstract class List[+A],其中类型参数 A 是协变的。 这意味着 Dog 是 Animal,则 List[Dog] 是 List[Animal]
    在这里插入图片描述
    先定义两个类AnimalDog , 其中Dog 继承Animal

      class Animal(val name: String) {
        override def toString: String = s"Animal $name "
      }
    
      class Dog(name: String) extends Animal(name) {
        override def toString: String = s"Dog $name "
      }
    
      class Cat(name: String) extends Animal(name) {
        override def toString: String = s"Cat $name "
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    使用了List的定义

      // 定义侧协变
      def printAnimalNames(animals: List[Animal]): Unit = animals foreach (animal => println(animal.name))
    
      val dogList: List[Dog] = List(
        Dog("Fido"),
        Dog("Rex")
      )
      val animalList = List(
        Animal("Whiskers"),
        Animal("Tom")
      )
      printAnimalNames(dogList) // 
      printAnimalNames(animalList)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    Scala的Array类声明为不变:
    在这里插入图片描述
    测试下几乎相同的代码(只有类型不一样)

     def printAnimalNames2(animals: Array[Animal]): Unit = println(animals.mkString(", "))
    
      val animals: Array[Animal] = Array(
        Animal("Anne"),
        Animal("Nico")
      )
      val dogs: Array[Dog] = Array(
        Dog("Coco"),
        Dog("Dja")
      )
      printAnimalNames2(animals) // Animal Anne , Animal Nico
      //  printAnimalNames2(dogs)// Required: Array[lang.oo.Variance.Animal]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    再测试就会报错。因为,Array[Dog] 不是 Array[Animal] 的子类

    2. 使用侧协变

    即使不定义协变,我们也能使用协变(比如在Java中 ?extends T
    在Scala中,T <: Type 就表示T 是Type的子类

      /**
       * 协变 covariance 希望接受超类集合的地方可以接受子类集合
       * 使用侧协变(使用点型变)
       */
      def playWithAnimals[T <: Animal](pets: Array[T]): Unit = println(pets.mkString(", "))
      
      def playJustWithAnimals(pets: Array[Animal]): Unit = println(pets.mkString(", "))
    
      playWithAnimals(animals) //Animal Anne , Animal Nico
      playWithAnimals(dogs) // Dog Coco , Dog Dja
      playJustWithAnimals(animals) //Animal Anne , Animal Nico
      //  playJustWithAnimals(dogs)// Required: Array[lang.oo.Types.Animal]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    逆变

    1. 定义侧逆变

    通过使用注释 -A,可以使一个泛型类的类型参数 A 成为逆变。 与协变类似,这会在类及其类型参数之间创建一个子类型关系,但其作用与协变完全相反。 也就是说,对于某个类 class Writer[-A] ,使 A 逆变意味着对于两种类型 A 和 B,如果 A 是 B 的子类型,那么 Writer[B] 是 Writer[A] 的子类型

      //定义侧协变 (声明点型变)
      abstract class Printer[-A] {
        def print(value: A): Unit
      }
    
      class AnimalPrinter extends Printer[Animal] {
        def print(animal: Animal): Unit =
          println("The animal's name is: " + animal.name)
      }
    
      class DogPrinter extends Printer[Dog] {
        def print(dog: Dog): Unit =
          println("The dog's name is: " + dog.name)
      }
    
      val myDog: Dog = Dog("Boots")
    
      def printMyDog(printer: Printer[Dog]): Unit = {
        printer.print(myDog)
      }
    
      val dogPrinter: Printer[Dog] = new DogPrinter
      val animalPrinter: Printer[Animal] = new AnimalPrinter
    
      printMyDog(dogPrinter) //The dog's name is: Boots
      printMyDog(animalPrinter) //The dog's name is: Boots
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    2. 使用侧逆变

    继续使用上面Animal和Dog

    在Scala中 T >: Dog 就表示T是Dog的父类

      /**
       * 逆变 contravariance 希望接受子类集合的地方可以接受超类集合
       */
      def playWithDogs[T >: Dog](pets: Array[T]): Unit = println(pets.mkString(", "))
    
      def playJustWithDogs(pets: Array[Dog]): Unit = println(pets.mkString(", "))
    
      playWithDogs(dogs) //Dog Coco , Dog Dja
      playWithDogs(animals) //Animal Anne , Animal Nico
      playJustWithDogs(dogs) //Dog Coco , Dog Dja
      //  playJustWithDogs(animals)//Required: Array[lang.oo.Types.Dog]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    不变

    默认情况下,Scala中的泛型类是不变的。 这意味着它们既不是协变的也不是逆变的。 在下例中,类 Container 是不变的。 Container[Cat] 不是 Container[Animal],反之亦然。

    class Container[A](value: A) {
      private var _value: A = value
      def getValue: A = _value
      def setValue(value: A): Unit = {
        _value = value
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    可能看起来一个 Container[Cat] 自然也应该是一个 Container[Animal],但允许一个可变的泛型类成为协变并不安全。 在这个例子中,Container 是不变的非常重要。 假设 Container 实际上是协变的,下面的情况可能会发生:

    val catContainer: Container[Cat] = new Container(Cat("Felix"))
    val animalContainer: Container[Animal] = catContainer
    animalContainer.setValue(Dog("Spot"))
    val cat: Cat = catContainer.getValue // 离谱~  我们最终会将一只狗作为值分配给一只猫
    
    • 1
    • 2
    • 3
    • 4

    幸运的是,编译器在此之前就会阻止我们。

    测试代码

    // Variance.scala
    /**
     * 型变是复杂类型的子类型关系与其组件类型的子类型关系的相关性。
     * Scala支持 泛型类 的类型参数的型变注释,允许它们是协变的,逆变的,或在没有使用注释的情况下是不变的。
     *
     * 协变 covariance 希望接受父类集合的地方可以接受子类集合
     * 逆变 contravariance 希望接受子类集合的地方可以接受超类集合
     *
     * class Foo[+A] // A covariant class
     * class Bar[-A] // A contravariant class
     * class Baz[A]  // An invariant class
     *
     */
    object Variance extends App {
    
      class Animal(val name: String) {
        override def toString: String = s"Animal $name "
      }
    
      class Dog(name: String) extends Animal(name) {
        override def toString: String = s"Dog $name "
      }
    
      class Cat(name: String) extends Animal(name) {
        override def toString: String = s"Cat $name "
      }
    
      // 定义侧协变
      def printAnimalNames(animals: List[Animal]): Unit = println(animals.mkString(", "))
    
      val dogList: List[Dog] = List(
        Dog("Fido"),
        Dog("Rex")
      )
      val animalList = List(
        Animal("Whiskers"),
        Animal("Tom")
      )
      printAnimalNames(dogList) //Dog Fido , Dog Rex
      printAnimalNames(animalList) //Animal Whiskers , Animal Tom
    
      def printAnimalNames2(animals: Array[Animal]): Unit = println(animals.mkString(", "))
    
      val animals: Array[Animal] = Array(
        Animal("Anne"),
        Animal("Nico")
      )
      val dogs: Array[Dog] = Array(
        Dog("Coco"),
        Dog("Dja")
      )
      printAnimalNames2(animals) // Animal Anne , Animal Nico
      //  printAnimalNames2(dogs)// Required: Array[lang.oo.Variance.Animal]
    
      /**
       * 协变 covariance 希望接受超类集合的地方可以接受子类集合
       * 使用侧协变(使用点型变)
       */
      def playWithAnimals[T <: Animal](pets: Array[T]): Unit = println(pets.mkString(", "))
    
      def playJustWithAnimals(pets: Array[Animal]): Unit = println(pets.mkString(", "))
    
      playWithAnimals(animals) //Animal Anne , Animal Nico
      playWithAnimals(dogs) // Dog Coco , Dog Dja
      playJustWithAnimals(animals) //Animal Anne , Animal Nico
      //  playJustWithAnimals(dogs)// Required: Array[lang.oo.Types.Animal]
    
    
      /**
       * 逆变 contravariance 希望接受子类集合的地方可以接受超类集合
       */
      def playWithDogs[T >: Dog](pets: Array[T]): Unit = println(pets.mkString(", "))
    
      def playJustWithDogs(pets: Array[Dog]): Unit = println(pets.mkString(", "))
    
      playWithDogs(dogs) //Dog Coco , Dog Dja
      playWithDogs(animals) //Animal Anne , Animal Nico
      playJustWithDogs(dogs) //Dog Coco , Dog Dja
      //  playJustWithDogs(animals)//Required: Array[lang.oo.Types.Dog]
    
    
      //定义侧协变 (声明点型变)
      abstract class Printer[-A] {
        def print(value: A): Unit
      }
    
      class AnimalPrinter extends Printer[Animal] {
        def print(animal: Animal): Unit =
          println("The animal's name is: " + animal.name)
      }
    
      class DogPrinter extends Printer[Dog] {
        def print(dog: Dog): Unit =
          println("The dog's name is: " + dog.name)
      }
    
      val myDog: Dog = Dog("Boots")
    
      def printMyDog(printer: Printer[Dog]): Unit = {
        printer.print(myDog)
      }
    
      val dogPrinter: Printer[Dog] = new DogPrinter
      val animalPrinter: Printer[Animal] = new AnimalPrinter
    
      printMyDog(dogPrinter) //The dog's name is: Boots
      printMyDog(animalPrinter) //The dog's name is: Boots
    
    
      // 不变
      abstract class Iterator[T] {
        def hasNext: Boolean
    
        def next: T
      }
    
      class Container[A](value: A) {
        private var _value: A = value
    
        def getValue: A = _value
    
        def setValue(value: A): Unit = {
          _value = value
        }
      }
    
      val catContainer: Container[Cat] = new Container(Cat("Felix"))
      val animalContainer: Container[Animal] = catContainer
      animalContainer.setValue(Dog("Spot"))
      val cat: Cat = catContainer.getValue // 我们最终会将一只狗作为值分配给一只猫
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
  • 相关阅读:
    Matlab如何提取论文插图中的渐变色?一招轻松搞定
    二代水务系统架构设计分享——DDD+个性化
    Android MediaCodec硬件解码视频播放
    学习笔记第十九天
    C++ Reference: Standard C++ Library reference: C Library: cwchar: wcstok
    每日三题 9.30
    服务器部署Oracle,并实现客户端远程连接
    acwing算法基础之基础算法--高精度加法算法
    排列数字(DFS)
    腾讯云3年云服务器价格及购买教程
  • 原文地址:https://blog.csdn.net/m0_52313753/article/details/126253700