콘텐츠로 이동

2023 03 10

2023-03-10

Scala Generic Variance

  • Covariance

    • + 심볼로 선언되어 있다면 Covariant
    • Covariance는 Type[Child]를 Type[Parent]에 할당시킬 수 있음
      • Type[Child] = Type[Parent]
        class Animal
        class Cat extends Animal
        class Dog extends Animal
        
        class Cage[+T](val animal: T) // T보다 상위에 있는 친구를 할당 할 수 있어요
        
        val catCage: Cage[Cat] = new Cage[Cat](new Cat)
        val animalCage: Cage[Animal] = catCage
        
    • 자바의 ? extends 와 문법이 비슷하다고 생각하면 됨
  • Contravariance

    • - 심볼로 선언되어 있다면 Contravariance
    • Contravariance는 Type[Parent]를 Type[Child]에 할당 시킬 수 있음
      • Type[Parent] = Type[Child]
        trait Writer[-T] {
          def write(item: T): Unit
        }
        
        class Animal
        class Cat extends Animal
        class Dog extends Animal
        
        val animalWriter: Writer[Animal] = new Writer[Animal] {
          def write(animal: Animal): Unit = println("Animal")
        }
        
        val catWriter: Writer[Cat] = animalWriter
        
    • 자바의 ? super 와 문법이 비슷하다고 보면 됨
  • Invariance
    • 그냥 딱 하나 쓰는거랑 똑같음