{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

Previous

\n", "

Next

\n", "

Tour of Scala

\n", "
\n", "\n", "# Variances\n", "\n", "Variance is the correlation of subtyping relationships of complex types and the subtyping relationships of their component types. Scala supports variance annotations of type parameters of [generic classes](generic-classes.ipynb), to allow them to be covariant, contravariant, or invariant if no annotations are used. The use of variance in the type system allows us to make intuitive connections between complex types, whereas the lack of variance can restrict the reuse of a class abstraction." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mclass\u001b[39m \u001b[36mFoo\u001b[39m\n", "defined \u001b[32mclass\u001b[39m \u001b[36mBar\u001b[39m\n", "defined \u001b[32mclass\u001b[39m \u001b[36mBaz\u001b[39m" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Foo[+A] // A covariant class\n", "class Bar[-A] // A contravariant class\n", "class Baz[A] // An invariant class" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Covariance\n", "\n", "A type parameter `A` of a generic class can be made covariant by using the annotation `+A`. For some `class List[+A]`, making `A` covariant implies that for two types `A` and `B` where `A` is a subtype of `B`, then `List[A]` is a subtype of `List[B]`. This allows us to make very useful and intuitive subtyping relationships using generics.\n", "\n", "Consider this simple class structure:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mclass\u001b[39m \u001b[36mAnimal\u001b[39m\n", "defined \u001b[32mclass\u001b[39m \u001b[36mCat\u001b[39m\n", "defined \u001b[32mclass\u001b[39m \u001b[36mDog\u001b[39m" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abstract class Animal {\n", " def name: String\n", "}\n", "case class Cat(name: String) extends Animal\n", "case class Dog(name: String) extends Animal" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Both `Cat` and `Dog` are subtypes of `Animal`. The Scala standard library has a generic immutable `sealed abstract class List[+A]` class, where the type parameter `A` is covariant. This means that a `List[Cat]` is a `List[Animal]` and a `List[Dog]` is also a `List[Animal]`. Intuitively, it makes sense that a list of cats and a list of dogs are each lists of animals, and you should be able to substitute either of them for a `List[Animal]`.\n", "\n", "In the following example, the method `printAnimalNames` will accept a list of animals as an argument and print their names each on a new line. If `List[A]` were not covariant, the last two method calls would not compile, which would severely limit the usefulness of the `printAnimalNames` method." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mobject\u001b[39m \u001b[36mCovarianceTest\u001b[39m" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "object CovarianceTest extends App {\n", " def printAnimalNames(animals: List[Animal]): Unit = {\n", " animals.foreach { animal =>\n", " println(animal.name)\n", " }\n", " }\n", "\n", " val cats: List[Cat] = List(Cat(\"Whiskers\"), Cat(\"Tom\"))\n", " val dogs: List[Dog] = List(Dog(\"Fido\"), Dog(\"Rex\"))\n", "\n", " printAnimalNames(cats)\n", " // Whiskers\n", " // Tom\n", "\n", " printAnimalNames(dogs)\n", " // Fido\n", " // Rex\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Contravariance\n", "\n", "A type parameter `A` of a generic class can be made contravariant by using the annotation `-A`. This creates a subtyping relationship between the class and its type parameter that is similar, but opposite to what we get with covariance. That is, for some `class Writer[-A]`, making `A` contravariant implies that for two types `A` and `B` where `A` is a subtype of `B`, `Writer[B]` is a subtype of `Writer[A]`.\n", "\n", "Consider the `Cat`, `Dog`, and `Animal` classes defined above for the following example:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mclass\u001b[39m \u001b[36mPrinter\u001b[39m" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abstract class Printer[-A] {\n", " def print(value: A): Unit\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A `Printer[A]` is a simple class that knows how to print out some type `A`. Let's define some subclasses for specific types:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mclass\u001b[39m \u001b[36mAnimalPrinter\u001b[39m\n", "defined \u001b[32mclass\u001b[39m \u001b[36mCatPrinter\u001b[39m" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class AnimalPrinter extends Printer[Animal] {\n", " def print(animal: Animal): Unit =\n", " println(\"The animal's name is: \" + animal.name)\n", "}\n", "\n", "class CatPrinter extends Printer[Cat] {\n", " def print(cat: Cat): Unit =\n", " println(\"The cat's name is: \" + cat.name)\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a `Printer[Cat]` knows how to print any `Cat` to the console, and a `Printer[Animal]` knows how to print any `Animal` to the console, it makes sense that a `Printer[Animal]` would also know how to print any `Cat`. The inverse relationship does not apply, because a `Printer[Cat]` does not know how to print any `Animal` to the console. Therefore, we should be able to substitute a `Printer[Animal]` for a `Printer[Cat]`, if we wish, and making `Printer[A]` contravariant allows us to do exactly that." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mobject\u001b[39m \u001b[36mContravarianceTest\u001b[39m" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "object ContravarianceTest extends App {\n", " val myCat: Cat = Cat(\"Boots\")\n", "\n", " def printMyCat(printer: Printer[Cat]): Unit = {\n", " printer.print(myCat)\n", " }\n", "\n", " val catPrinter: Printer[Cat] = new CatPrinter\n", " val animalPrinter: Printer[Animal] = new AnimalPrinter\n", "\n", " printMyCat(catPrinter)\n", " printMyCat(animalPrinter)\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The output of this program will be:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "The cat's name is: Boots\n", "The animal's name is: Boots\n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Invariance\n", "\n", "Generic classes in Scala are invariant by default. This means that they are neither covariant nor contravariant. In the context of the following example, `Container` class is invariant. A `Container[Cat]` is _not_ a `Container[Animal]`, nor is the reverse true." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mclass\u001b[39m \u001b[36mContainer\u001b[39m" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Container[A](value: A) {\n", " private var _value: A = value\n", " def getValue: A = _value\n", " def setValue(value: A): Unit = {\n", " _value = value\n", " }\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It may seem like a `Container[Cat]` should naturally also be a `Container[Animal]`, but allowing a mutable generic class to be covariant would not be safe. In this example, it is very important that `Container` is invariant. Supposing `Container` was actually covariant, something like this could happen:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "cmd7.sc:2: type mismatch;\n", " found : cmd7.this.cmd6.Container[cmd7.this.cmd1.Cat]\n", " required: cmd7.this.cmd6.Container[cmd7.this.cmd1.Animal]\n", "Note: cmd7.this.cmd1.Cat <: cmd7.this.cmd1.Animal, but class Container is invariant in type A.\n", "You may wish to define A as +A instead. (SLS 4.5)\n", "val animalContainer: Container[Animal] = catContainer\n", " ^Compilation Failed" ] }, { "ename": "", "evalue": "", "output_type": "error", "traceback": [ "Compilation Failed" ] } ], "source": [ "val catContainer: Container[Cat] = new Container(Cat(\"Felix\"))\n", "val animalContainer: Container[Animal] = catContainer\n", "animalContainer.setValue(Dog(\"Spot\"))\n", "val cat: Cat = catContainer.getValue // Oops, we'd end up with a Dog assigned to a Cat" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fortunately, the compiler stops us long before we could get this far.\n", "\n", "### Other Examples\n", "\n", "Another example that can help one understand variance is `trait Function1[-T, +R]` from the Scala standard library. `Function1` represents a function with one argument, where the first type parameter `T` represents the argument type, and the second type parameter `R` represents the return type. A `Function1` is contravariant over its argument type, and covariant over its return type. For this example we'll use the literal notation `A => B` to represent a `Function1[A, B]`.\n", "\n", "Assume the similar `Cat`, `Dog`, `Animal` inheritance tree used earlier, plus the following:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mclass\u001b[39m \u001b[36mSmallAnimal\u001b[39m\n", "defined \u001b[32mclass\u001b[39m \u001b[36mMouse\u001b[39m" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abstract class SmallAnimal extends Animal\n", "case class Mouse(name: String) extends SmallAnimal" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Suppose we're working with functions that accept types of animals, and return the types of food they eat. If we would like a `Cat => SmallAnimal` (because cats eat small animals), but are given a `Animal => Mouse` instead, our program will still work. Intuitively an `Animal => Mouse` will still accept a `Cat` as an argument, because a `Cat` is an `Animal`, and it returns a `Mouse`, which is also a `SmallAnimal`. Since we can safely and invisibly substitute the former for the latter, we can say `Animal => Mouse` is a subtype of `Cat => SmallAnimal`.\n", "\n", "### Comparison With Other Languages\n", "\n", "Variance is supported in different ways by some languages that are similar to Scala. For example, variance annotations in Scala closely resemble those in C#, where the annotations are added when a class abstraction is defined (declaration-site variance). In Java, however, variance annotations are given by clients when a class abstraction is used (use-site variance).\n", "

Previous

\n", "

Next

\n", "

Tour of Scala

\n", "
" ] } ], "metadata": { "kernelspec": { "display_name": "Scala (2.13)", "language": "scala", "name": "scala213" }, "language_info": { "codemirror_mode": "text/x-scala", "file_extension": ".scala", "mimetype": "text/x-scala", "name": "scala", "nbconvert_exporter": "script", "version": "2.13.1" } }, "nbformat": 4, "nbformat_minor": 4 }