liveBook · Manning

Subtyping

As explained in Functional Programming in Scala, Second Edition

Subtyping is a type-system relationship in which values of one type may be used where values of another, more general type are expected.

Subtyping lets a value of one type stand where a more general type is expected. In a Free program, covariance makes Free[Console, A] usable as Free[[x] =>> Console[x] | Files[x], A]. section 13.5.1

Combining file and console effects

A file-reading operation returns Free[Files, List[String]], while printing returns Free[Console, Unit]. Without subtyping, composing them produces a type mismatch. A union type can express the combined effect: def cat(file: String): Free[[x] =>> Files[x] | Console[x], Unit].

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Descends from a motivating type error into covariance, contravariant positions, and mechanically widened type parameters.
Examples
Uses a cat program that reads lines from Files and prints them through Console.
What it assumes
Assumes Scala type parameters and Free-program syntax while developing variance concerns through compiler errors.
What you can do after
Build it from scratch by widening Free effect types and correcting flatMap variance errors.
How it connects
Connects subtyping with covariance, variance, union types, flatMap, and Free programs.

Also explained in

Compare how 4 books explain subtyping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.