- Concepts of Programming Languages

Subtyping

Instructor:

Learning Objectives

What should the type relationship between parameterized types be?

  • Identify read and write restrictions on parametric types

Subtyping

  • Static and dynamic type
    1. A x = new A ();
    2. B y = new B ();
    3. x = y; // B ok when A expected
  • Method parameters
    1. void aConsumer (A x) { ... }
    2. aConsumer (new B()); // B ok when A expected
  • Method results
    1. B bProducer () { ... }
    2. A x = bProducer (); // B ok when A expected
  • Safe to use an instance of B when an A is expected
  • B is a subtype of A: written B<:A
    • If y:B and B<:A then y:A (upcast)
  • Subtyping is not just subclassing: parametric polymorphism

Subtyping Order: Top

  • Subtyping relation <: is a partial order on types
    • reflexive: X<:X
    • transitive: if Duck<:Bird and Bird<:Animal then Duck<:Animal
  • Some PLs have a Top type: X<:Top for all X (greater than all other types)
  • In Java: java.lang.Object above reference types
  • In Scala: scala.Any above all types, scala.AnyRef above reference types
    1. val xs:List[AnyRef] = List ("hello", List(1))
    2. val ys:List[Any] = List ("hello", 1)

Subtyping Order: Bottom

  • Most PLs do not have a Bottom<:X for all X (less than all other types)
  • In Scala Type Hierarchy: Nothing is Bottom type (empty, no instances)

  • For typing neutral elements of parameterized types, e.g. Nil

    1. {runnable}
    2. // EXERCISE
    3. // 1. Compile, what happens?
    4. // 2. Try changing type nil: List[String] to nil: List[Nothing], what happens?
    5. val nil: List[String] = Nil
    6. val xs1 = "hello" :: nil
    7. val xs2 = 1 :: nil
    8. xs1
    9. xs2
  • Type inference

    • Nil : List[Nothing] and
    • Nothing <: X
    • (X :: List[Nothing]) : List[X]

Type-Invariant Containers

Type-invariant Box[X]

  1. enum Animal:
  2. case Bird(name: String)
  3. case Cat(name: String)
  4. def name: String
  5. end Animal
  6. case class Box[X](var content: X)
  • Create concrete boxes

    1. val birdBox = Box[Bird](Bird("Feathers"))
    2. val catBox = Box[Cat](Cat("Fluffy"))
  • Create an abstract box

    1. var animalBox = Box[Animal](Bird("Feathers"))
    2. animalBox.content = Cat("Fluffy")
  • Alias boxes

    1. animalBox = birdBox
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

case class Box[X](var content: X)

val birdBox = Box[Bird](Bird("Feathers"))
val catBox  = Box[Cat](Cat("Fluffy"))

var animalBox = Box[Animal](Bird("Feathers"))
animalBox.content = Cat("Fluffy")

// 1. Compile, what happens?
animalBox = birdBox
  • Assignment animalBox = birdBox not allowed because Box[Bird] is not a subtype of Box[Animal]
  • Why not Box[Bird]<:Box[Animal]?

    Box is invariant in its type parameter X

Type-Invariant Containers

What would go wrong if we allow assignment?

  1. val birdBox = Box[Bird](Bird("Feathers"))
  2. var animalBox: Box[Animal] = birdBox // does not compile, but can force compiler to accept with a cast birdBox.asInstanceOf[Box[Animal]]
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

case class Box[X](var content: X)

val birdBox = Box[Bird](Bird("Feathers"))
val catBox  = Box[Cat](Cat("Fluffy"))

var animalBox = Box[Animal](Bird("Feathers"))
animalBox.content = Cat("Fluffy")

// Invariant type annotation Box[X] means the content is allowed to be readable and writable
// 1. Compile, what happens?
// 2. Force compiler to accept assignment with a cast birdBox.asInstanceOf[Box[Animal]], what happens?
animalBox = birdBox

val animal: Animal = animalBox.content

animalBox.content = Cat("Fluffy")
animalBox.content

// 3. Now that we got access through both animalBox and birdBox, read from the bird box, what happens?
// birdBox.content

Read bird as animal

  1. val animal: Animal = animalBox.content

Put cat into animal box

  1. animalBox.content = Cat("Fluffy")

Bird box alias promises to deliver a bird, but now contains a cat!

  1. val bird: Bird = birdBox.content
  • Writing to aliased container would create type violations at runtime!

Type-Covariant Containers

What if we disallow modifying boxes?

  1. case class ImmutableBox[+X](val content: X)
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

// Covariant annotation +X requires content to be read-only
// 1. Try removing +, what happens?
// 2. Try changing val to var, what happens?
case class ImmutableBox[+X](val content: X)

val birdBox = ImmutableBox[Bird](Bird("Feathers"))
val animalBox: ImmutableBox[Animal] = birdBox

animalBox.content

// 3. Try writing to animalBox, what happens?
// animalBox.content = Cat("Fluffy")

birdBox.content

Create and alias boxes

  1. val birdBox = ImmutableBox(Bird("Feathers"))
  2. val animalBox: ImmutableBox[Animal] = birdBox

Read animal

  1. val animal = animalBox.content

Compile error, cannot reassign to val

  1. animalBox.content = Cat("Fluffy")
  • ImmutableBox is covariant in X

  • Covariance type annotation +X can only be applied to read-only structures

Covariant Boxes

What is the practical relevance?

  • Generic functions that work for all animal boxes

    1. def printAnimalName(b: ImmutableBox[Animal]) =
    2. println(b.content.name)
  • Print some concrete boxes

    1. val birdBox = ImmutableBox[Bird](Bird("Feathers"))
    2. val catBox = ImmutableBox[Cat](Cat("Fluffy"))
    3. printAnimalName(birdBox) // would not compile for def printAnimalName(b: Box[Animal])
    4. printAnimalName(catBox) // would not compile

Scala Lists are Covariant

What is the practical relevance?

  1. def printAnimalNames(animals: List[Animal]) =
  2. for a <- animals do println(a.name)
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

// 1. Compile, what happens?
// 2. Try changing List[Animal] to Array[Animal] in argument and lists below, what happens?
def printAnimalNames(animals: List[Animal]) =
  for a <- animals do println(a.name)
end printAnimalNames

val birds = List[Bird](Bird("Feathers"), Bird("Chirpy"))
val cats  = List[Cat](Cat("Fluffy"), Cat("Whiskers"))
printAnimalNames(birds)
printAnimalNames(cats)
  • Print some concrete lists

    1. val birds: List[Bird] = List(Bird("Feathers"), Bird("Chirpy"))
    2. val cats: List[Cat] = List(Cat("Fluffy"), Cat("Whiskers"))
    3. printAnimalNames(birds) // would not compile if List was not covariant
    4. printAnimalNames(cats) // would not compile
  • List must be covariant to allow printAnimalNames with concrete arguments of type List[Bird] and List[Cat]!

Scala Arrays are Invariant

  1. def printAnimalNames(animals: Array[Animal]) =
  2. for a <- animals do println(a.name)
  3. val birds = Array[Bird](Bird("Feathers"), Bird("Chirpy"))
  4. printAnimalNames(birds)
  • Compile error

    1. printAnimalNames(birds)
    2. ^^^^^
    3. Found: (birds : Array[Bird])
    4. Required: Array[Animal]
  • Scala and Java arrays are readable and writable

    • Scala arrays are invariant: compile error when writing to alias
    • Java arrays are covariant: runtime exception when writing to alias

Covariant Wildcard

How can we still print arrays generically?

enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

// Arrays are writable, but printAnimalNames does not write
// 1. Compile, what happens?
// 1. Try changing animals to covariant type wildcard Array[? <: Animal], what happens?
// 2. Try writing to animals: animals(0) = Cat("Fluffy"), what happens?
def printAnimalNames(animals: Array[Animal]) =  
  for a <- animals do println(a.name)
end printAnimalNames

val birds = Array[Bird](Bird("Feathers"), Bird("Chirpy"))
val cats  = Array[Cat](Cat("Fluffy"), Cat("Whiskers"))
printAnimalNames(birds)
printAnimalNames(cats)
  • Use a covariant wildcard to make array read-only

    1. def printAnimalNames(animals: Array[? <: Animal]) =
    2. for a <- animals do println(a.name)
    3. val birds: Array[Bird] = Array (Bird("Feathers"), Bird("Chirpy"))
    4. printAnimalNames(birds) // compiles
  • Cannot create required instance of type ? for writing to Array[? <: Animal]

    1. animals(0) = Cat("Fluffy")
    2. ^^^^^^^^^^^^^
    3. Found: Cat
    4. Required: animals.T

What about Writing?

Can we pass a Box[Animal] where a Box[Cat] is expected?

  1. def putCat(box: Box[Cat]) =
  2. box.content = Cat("Fluffy")
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

// birds and cats can do different things
extension (b: Bird)
  def chirp = "chirp"
extension (c: Cat)
  def meouw = "meouw"

case class Box[X](var content: X)

def putCat(box: Box[Cat]) =
  box.content = Cat("Fluffy")

val animalBox = Box[Animal](Cat("Whiskers"))
animalBox.content = Cat("Fluffy")

// 1. Compile, what happens?
// 2. Force compiling with cast animalBox.asInstanceOf[Box[Cat]], what happens?
// 3. Since putCat is promised a Box[Cat] its content can meouw: make println(box.content.meouw) the first line in putCat, what happens?
// 4. Put a bird into the box: animalBox.content = Bird("Feathers") before passing it to putCat, what happens?
putCat(animalBox)

println(animalBox.content.name)
  • Unable to pass in a box of animal

    1. val animalBox = Box[Animal](Cat("Whiskers"))
    2. putCat(animalBox)
    3. ^^^^^^^^^
    4. Found: (animalBox : Box[Animal])
    5. Required: Box[Cat]
  • Because the animal box could contain a bird (problematic if putCat would read)

    1. val animalBox: Box[Animal] = Box(Bird("Feathers"))
    2. putCat(animalBox)

Contravariance

What if we disallow reading?

  1. class MutableBox[-X](content: X):
  2. private var x: X = content
  3. def put(elem: X)= x=elem
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

// birds and cats can do different things
extension (b: Bird)
  def chirp = "chirp"
extension (c: Cat)
  def meouw = "meouw"

class MutableBox[-X](content: X):
  private var x = content
  def put(elem: X) = x=elem

// 1. Compile, what happens?
// 2. Try println(box.content.meouw) as first line in putCat, what happens?
// 3. Put a bird into the box before passing it to putCat: animalBox.put(Bird("Feathers")), what happens?
def putCat(box: MutableBox[Cat]) =
  box.put(Cat("Fluffy"))

val animalBox = MutableBox[Animal](Cat("Whiskers"))
animalBox.put(Cat("Fluffy"))

putCat(animalBox)

Create and alias boxex

  1. def putCat(box: MutableBox[Cat]) = box.put(Cat("Fluffy"))
  2. val animalBox = new MutableBox[Animal](Cat("Whiskers"))
  3. val catBox: MutableBox[Cat] = animalBox

Writing through both aliases

  1. catBox.put(Cat("Fluffy"))
  2. putCat(animalBox)

Reading not allowed

  1. catBox.content
  • MutableBox is contravariant in X

  • Contravariance type annotation -X can only be applied to write-only structures

Contravariance allows Degraded Read

We can use top-type Any to refer to any object

  1. class MutableBox[-X](content: X):
  2. private var x: X = content
  3. def put(elem: X) : Unit = x = elem
  4. def get : Any = x
  5. def putCat(box: MutableBox[Cat]) = box.put(Cat("Fluffy"))
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

// birds and cats can do different things
extension (b: Bird)
  def chirp = "chirp"
extension (c: Cat)
  def meouw = "meouw"

class MutableBox[-X](content: X):
  private var x = content
  def put(elem: X) = x=elem
  def get: Any = x

def putCat(box: MutableBox[Cat]) =
  box.put(Cat("Fluffy"))

val animalBox = MutableBox[Animal](Cat("Whiskers"))
animalBox.put(Bird("Feathers"))

putCat(animalBox)

val animal = animalBox.get
animal

// recover concrete types with pattern matching
animal match
  case c: Cat => println(c.meouw)
  case b: Bird => println(b.chirp)
  • Create box and modify it

    1. val animalBox: MutableBox[Animal] = new MutableBox(Bird("Feathers"))
    2. var animal: Any = animalBox.get
    3. putCat(animalBox)
    4. animal = animalBox.get // animal: Any
  • Recover concrete types using pattern matching

    1. animal match
    2. case c: Cat => println(c.meouw)
    3. case b: Bird => println(b.chirp)

Contravariant Wildcard

Can we pass List[Animal] where List[Cat] is expected?

  1. def addFluffy(cats: List[Cat]) =
  2. Cat("Fluffy") :: cats
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

extension (b: Bird)
  def chirp = "chirp"
extension (c: Cat)
  def meouw = "meouw"

def addFluffy(cats: List[Cat]) =  
  Cat("Fluffy") :: cats

// 1. Compile, what happens?
// 2. Change addFluffy: first println(cats.map(_.meouw).mkString), what happens?
// 3. Create a val animals = List[Animal](Bird("Feathers"), Cat("Whiskers")) and pass to addFluffy, what happens?
// 4. Force compiler to accept by casting animals.asInstanceOf[List[Cat]], what happens?
val cats = List[Cat](Cat("Whiskers"))
val moreCats = addFluffy(cats)
  • Add to a list of cats

    1. val cats: List[Cat] = List(Cat("Whiskers"))
    2. val moreCats: List[Cat] = addFluffy(cats) // ok
  • Add to a list of animals

    1. val animals: List[Animal] = List(Bird("Feathers"), Cat("Whiskers"))
    2. addFluffy(animals)
    3. ^^^^^^^
    4. Found: (animals : List[Animal])
    5. Required: List[Cat]

Contravariant Wildcard

Reading cats in addFluffy was the problem, make list readable only as top-type

  1. def addFluffy(cats: List[? >: Cat]) =
  2. Cat("Fluffy") :: cats
enum Animal:
  case Bird(name: String)
  case Cat(name: String)
  def name: String
end Animal

import Animal.*

extension (b: Bird)
  def chirp = "chirp"
extension (c: Cat)
  def meouw = "meouw"

// 1. Compile, what happens?
// 2. Change to contravariant wildcard List[? >: Cat], what happens?
// 3. Try to meouw the cats in addFluffy using println(cats.map(_.meouw).mkString), what happens?
// 4. Change meouwing to print the cats in addFluffy using println(cats.map(_.toString).mkString), what happens?
// 5. Inspect the types of moreCats and moreAnimals, what are they?
// 6. Change addFluffy to use a contravariant type parameter: addFluffy[X >: Cat](cats: List[X]) : List[X], what happens?
// 7. Add to a list of ints: addFluffy(List(1,2,3)), what happens?
def addFluffy(cats: List[Cat]) =
  Cat("Fluffy") :: cats

val cats = List[Cat](Cat("Whiskers"))
val moreCats = addFluffy(cats)
moreCats

val animals = List[Animal](Bird("Feathers"), Cat("Whiskers"))
val moreAnimals = addFluffy(animals)
moreAnimals
  • Contravariant wildcard ? >: X

  • Add to a list of animals

    1. val animals: List[Animal] = List(Bird("Feathers"), Cat("Whiskers"))
    2. val moreAnimals: List[Any] = addFluffy(animals)
  • Can we do better than List[Any]?

Contravariant Type Parameter

  • Use a contravariant type parameter rather than a wildcard
  1. def addFluffy[X >: Cat](cats: List[X]) : List[X] =
  2. Cat("Fluffy") :: cats
  • Add to lists of cats, animals, other things
    1. val moreCats: List[Cat] = addFluffy(List[Cat](Cat("Whiskers")))
    2. val animals = List[Animal](Bird("Feathers"), Cat("Whiskers"))
    3. val moreAnimals: List[Animal] = addFluffy(animals)
    4. val more: List[Int | Cat] = addFluffy(List(1,2,3))

Summary

  • Subtype polymorphism: B<:A (B is a subtype of A)
  • Parametric polymorphism: T[X] parameterize class T with type parameter X
  • Covariant, contravariant, and invariant parametric types for B<:A
    Covariant Contravariant Invariant
    Readable Writable Read-write
    Relationship T[B] <: T[A] T[A] <: T[B] T[A]<>T[B]
    Box ImmutableBox[X] MutableBox[X] Box[X]
    Collection List[X] Array[X]
    Annotations T[+X] T[-X] T[X]
    Functions Unit=>X X=>Unit X=>X

Java Arrays are Covariant

  1. public static void main (String[] args) {
  2. B[] bs = new B[] { new B (), new B () };
  3. A[] as = bs; // OK, because covariant
  4. as[0] = new A (); // ArrayStoreException
  5. bs[0].g();
  6. }
  1. $ javac Driver.java
  2. $ java Driver
  3. Exception in thread "main" java.lang.ArrayStoreException: A
  4. at Driver.main(Driver.java:5)
  • Every assignment to object array dynamically checked!

Why?

  • For example, to sort
    1. static void sort(Object[] xs) { ... }
    2. String[] ss = ...;
    3. sort(ss); // requires covariance
  • With Java Generics
  1. static <X extends Comparable<? super X>> void sort(X[] xs) { ... }
  • In Scala
  1. def sort[X <: Comparable[? >: X]] (xs: Array[X]) = ...
  • Use
    1. class A implements Comparable<A>{}
    2. class B extends A {}
    3. B[] bs = ...;
    4. sort(bs); // B's are comparable as A's

Variance Annotations Example

  1. trait Source[+X] { def get () : X } // Covariant: read-only
  2. trait Sink [-X] { def put (x:X) : Unit } // Contravariant: write-only
  1. class Ref [ X] (var contents:X) // Invariant: read-write
  2. extends Source[X] with Sink[X]:
  3. def get () = contents
  4. def put (x:X) = contents = x
  • Create aliases
    1. val ref: Ref[Bird] = Ref(Bird("Feathers"))
    2. val src: Source[Animal] = ref
    3. val snk: Sink[Duck] = ref
  • Write to snk, read from ref and src
    1. val d = Duck("Quack")
    2. snk.put(d)
    3. val r = ref.get()
    4. val s = src.get()
  • What are the static and dynamic types of d, r, and s?

Variance Annotations Example

  1. trait Function[-X,+Y] { def apply(x:X) : Y } // Contravariant in X, covariant in Y
  • Covariant use

    1. // List[Int] <: Seq[Int], so Function[Int,List[Int]] <: Function[Int,Seq[Int]]
    2. val increment: Function[Seq[Int],Seq[Int]] = new Function[Seq[Int],List[Int]]:
    3. def apply(x: Seq[Int]) : List[Int] = x.map(_ + 1).toList
    4. // Int <: Any, so Function[Seq[Int],Int] <: Function[Seq[Int],Any]
    5. val length: Function[Seq[Int],Any] = new Function[Seq[Int],Int]:
    6. def apply(x: Seq[Int]) : Int = x.length
  • Contravariant use

    1. def chain(f: Function[List[Int],Seq[Int]], g: Function[Seq[Int],Any]) =
    2. (x:List[Int]) => g(f(x))
    3. chain(increment, length)

Variance Annotations

  1. trait Producer[+Y] { def apply () : Y } // Covariant
  2. trait Consumer[-X] { def apply (x:X) : Unit } // Contravariant
  3. trait Function[-X,+Y] { def apply (x:X) : Y } // Both
  4. trait Operator[X] { def apply (x:X) : X } // Invariant
  1. trait Producer[-Y] { def apply () : Y }
  2. ^
  3. error: contravariant type Y occurs in covariant position
  1. trait Consumer[+X] { def apply (x:X) : Unit }
  2. ^
  3. error: covariant type X occurs in contravariant position

Scastie integration for live coding in slides

highlight.js consistent with Scastie (Solarized light theme)

Hidden modal dialogs

Copy code

Scastie embedded Scala editor

Modal dialogs

# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-book fa-stack-1x fa-inverse"></i></span> Checked Casts - Recall lecture on safety ```java class A { int x; } class B extends A { float y; } class C extends A { char c; } void f (B b) { A a = b; // upcast always safe } void g (A a) { B b = (B) a; // downcast must be checked } f (new B()); // OK g (new C()); // ClassCastException ``` :fa fa-question-circle: What makes upcasting safe? What makes downcasting unsafe? ---

Let students evaluate and see types: xs1: List[String], xs2: List[String | Int]

* Ok, because `List[B] <: List[A]` * `List` is _covariant_ * If `B<:A` then `List[B]<:List[A]` * Generally, type constructor `T[-]` is _covariant_ if `B<:A` implies `T[B]<:T[A]`

- Outside the scope of this course - Bounded polymorphism (Java, C#, Scala, Flow) - Java's use-site variance and wildcards - Adhoc polymorphism, typeclasses, implicit params - Check out Scala and Typescript