strangerRidingCaml

7. Subtyping and Variance 본문

Type theory

7. Subtyping and Variance

woddlwoddl 2024. 5. 10. 02:33
728x90
Subtyping and Variance

Subtyping and Variance

Subtyping is a relationship between types where one type is considered a subtype of another type.

This relationship is often denoted as S <: T, meaning that type S is a subtype of type T.

Subtyping allows for more flexible type systems where a value of a subtype can be used wherever a value of its supertype is expected.

Variance is a property of type constructors, such as generic types or function types, that determines how the subtyping relationship is inherited by the constructed types.

There are three main variance annotations: covariant, contravariant, and invariant.

  • Covariant types preserve the subtyping relationship. For example, if S <: T, then List[S] <: List[T].
  • Contravariant types reverse the subtyping relationship. For example, if S <: T, then Function[T] <: Function[S].
  • Invariant types do not change the subtyping relationship. For example, List[T] is invariant in T.

Lab Activity: Implementing Subtyping and Variance

Let's implement a simple example of subtyping and variance in Python using classes and inheritance.


class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

def speak(animal):
    animal.speak()

def main():
    animal = Animal()
    dog = Dog()
    
    speak(animal)
    speak(dog)

if __name__ == "__main__":
    main()
  

In the lab activity, we define a base class `Animal` with a method `speak`.

We then define a subclass `Dog` that inherits from `Animal` and overrides the `speak` method.

We demonstrate subtyping by passing instances of both `Animal` and `Dog` to a function expecting an `Animal`.