Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 134 ยท Generics and Types

Variance: in and out

Understand Kotlin variance step by step: why List<Dog> is a List<Animal> but MutableList is not, how out and in work, use-site projections and the Java PECS rule.

Here is a puzzle that trips up almost everyone. A Dog is an Animal. So is a list of dogs a list of animals? If your function says fun feedAll(animals: List<Animal>), may you hand it a List<Dog>? In Kotlin the answer is yes. But if the function says fun adopt(shelter: MutableList<Animal>), you may not hand it a MutableList<Dog>. Same classes, opposite answers.

The rule behind it is called variance: how the subtype relationship of the type arguments (Dog is a subtype of Animal) carries over to the generic types built from them (List<Dog> versus List<Animal>). Kotlin has three possible answers: covariant (the relationship carries over, written out), contravariant (it reverses, written in), and invariant (it does not carry over, the default). This lesson explains each with code, shows the compiler errors, and ends with the Java comparison. If generics are new to you, read Generics first.

The setup

Every example uses the same small hierarchy:

Kotlin
open class Animal(val name: String)
class Dog(name: String) : Animal(name)
class Cat(name: String) : Animal(name)

Why mutable lists are invariant

Suppose Kotlin allowed a MutableList<Dog> wherever a MutableList<Animal> is expected. Watch what could happen:

Kotlin Why MutableList cannot be covariant (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler refuses the call addCat(dogs) with error: argument type mismatch: actual type is 'MutableList<Dog>', but 'MutableList<Animal>' was expected. Had it allowed the call, addCat would have slipped a Cat into a list that everyone else believes holds only dogs, and the line val first: Dog = dogs[1] would blow up at run time. The check protects you at compile time. So a type that you can both read from and write to must be invariant: MutableList<Dog> and MutableList<Animal> are unrelated types.

out: types that only produce values (covariance)

Look at the read-only List<out E>. It has get and iteration, but no add. It only ever hands out elements, never takes new ones. With only outgoing values, it is perfectly safe to see a list of dogs as a list of animals: everything that comes out is an Animal, which is exactly what the reader expects.

Kotlin List is covariant, so List of Dog is a List of Animal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You can give your own classes the same ability. Put out in front of the type parameter at the declaration, and the compiler checks that T is only used where values leave the class (return types, val properties):

Kotlin Declaring a covariant Producer with out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because Producer is declared with out T, a Producer<Dog> is a subtype of Producer<Animal>. Without out, the call adoptOne(breeder) would fail. A type that is covariant in T keeps the direction of the arrow: Dog is a subtype of Animal, so Producer<Dog> is a subtype of Producer<Animal>.

What if you break the promise and use T as a function parameter in an out class? The compiler stops you:

Kotlin out forbids T in parameter position (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error is type parameter 'T' is declared as 'out' but occurs in 'in' position in type 'T (of class Box<out T>)'. It points at the parameter of set; the private var value: T in the constructor is accepted, because private members are exempt. The reason is the same safety argument as before: if a Box<Dog> could be seen as a Box<Animal>, then set(Cat(...)) would store a cat in a dog box.

in: types that only consume values (contravariance)

Now the mirror image. Consider something that only takes values and never returns them, like a printer or a comparator. If you have a Sink<Animal>, something that can handle any animal, it can obviously also handle a dog. So a Sink<Animal> can be used where a Sink<Dog> is needed: the arrow reverses. This is contravariance, written in.

Kotlin Contravariant Sink with in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The most familiar contravariant type is the comparison. Comparable<in T> and Comparator<in T> are declared with in, so a comparator for animals can sort a list of dogs:

Kotlin A Comparator of Animal sorts Dogs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

sortedWith on a List<Dog> wants a Comparator<in Dog>; a Comparator<Animal> qualifies because the parameter is contravariant.

Function types are variant too

Function types follow the same rules: (A) -> B is Function1<in A, out B>. It consumes an A (contravariant) and produces a B (covariant). That is why you can pass a lambda that accepts any Animal and returns a Dog where a function (Dog) -> Animal is expected. Variance is working invisibly whenever you pass lambdas around (Function Types and Type Aliases).

Kotlin Function types: in for parameters, out for results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A function that accepts any Animal (it can certainly take a Dog) and returns a Dog (which is an Animal) is a valid (Dog) -> Animal. Parameters may be wider, results may be narrower.

A memory aid

Think of the type as a producer or a consumer:

The type only... Marker Direction Example
produces T (returns it) out T same as the arguments List<out E>, Producer<out T>
consumes T (takes it as parameter) in T reversed Comparator<in T>, Sink<in T>
does both no marker unrelated MutableList<E>, Array<T>

The Java community calls this PECS: Producer Extends, Consumer Super. In Java you write the variance every time you use a type (List<? extends Animal>, Comparator<? super Dog>). Kotlin lets you declare it once, in the class, and avoids the wildcard clutter everywhere else. That is declaration-site variance.

Use-site variance (type projections)

Sometimes you cannot change the class: MutableList and Array are both read and write, so they must stay invariant. But a particular function may only use one side. For that, Kotlin lets you project the type at the point of use, like Java wildcards. That is use-site variance.

Kotlin Projections at the use site

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Array<out Animal> means "an array of Animal or of some subtype; I will only read". That is why an Array<Dog> is accepted. Array<in Animal> means "an array of Animal or of some supertype; I will only write", so an Array<Any?> fits. The compiler enforces your promise inside the function:

Kotlin An out-projected list cannot be written (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler rejects list.add(...) with receiver type 'MutableList<out Animal>' contains out projection which prohibits the use of 'fun add(element: E): Boolean'. With an out projection the exact element type is unknown (it might be MutableList<Cat>). Reading and size are fine. When you see such a message, you have found the exact scenario variance exists to prevent.

Choosing: declaration-site or use-site?

  • Your own class only produces or only consumes T: declare out T or in T once. Every user benefits and signatures stay clean.
  • Your class both reads and writes T: keep it invariant. Offer read-only views as separate interfaces if needed (this is how List and MutableList are split).
  • You use someone else's invariant type, but your function reads only or writes only: add a projection (Array<out T>, MutableList<in T>) to accept more arguments.

When you write a function parameter whose type is a collection, accept the read-only List<T> or Collection<T> if you only read. It is covariant, so callers can pass List<Dog> for List<Animal> without ceremony. Reach for MutableList<T> only when you really modify the caller's collection.

Pitfalls

Covariant does not mean immutable at run time. A List<Animal> may be backed by an ArrayList that someone else mutates through a MutableList<Dog>. Variance is about what the type allows you to do, not about the object's real state.

out can hide behind private members. The rule on out positions applies to public API; private members are exempt in many cases because no outside code can misuse them. If the compiler accepts something you expected to be rejected, check whether the member is private.

Do not add out to everything. It is a statement about the contract of your class. If you later add a method that takes a T, you will have to remove out and break callers who relied on it.

Arrays are invariant in Kotlin. In Java, Dog[] is an Animal[], which compiles and then throws ArrayStoreException when you store a cat. Kotlin avoids the problem by making Array<T> invariant.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the compiler reject passing a MutableList<Dog> where a MutableList<Animal> is expected?

    A mutable list can be written to, so allowing the substitution would let any function insert a Cat into a list that other code believes contains only Dogs. Types that are read and written are invariant.
  2. 2. What does out T on interface Producer<out T> promise?

    out marks a covariant type parameter. The compiler allows it only where values come out of the class, which makes the subtype relationship carry over.
  3. 3. Which of these is contravariant in its type parameter?

    Comparator<in T> only consumes values of type T, so a Comparator<Animal> can be used where a Comparator<Dog> is needed. List is covariant, MutableList and Array are invariant.
  4. 4. What does the parameter type Array<out Animal> allow?

    A use-site out projection says you only read from the array. Because of that, an Array<Dog> (or any other subtype array) is accepted, and writing is forbidden.
  5. 5. How is the function type (Animal) -> Dog related to (Dog) -> Animal?

    Function types are contravariant in their parameters and covariant in their result. A function accepting any Animal handles a Dog, and a function returning a Dog returns an Animal, so it fits the narrower contract.

Summary

  • Variance describes how Dog being a subtype of Animal carries over to generic types such as List<Dog> and List<Animal>.
  • Types that read and write their parameter (MutableList<T>, Array<T>) are invariant; the compiler stops unsafe substitutions.
  • out T marks a producer (covariant): T may appear only in output positions, and Producer<Dog> is a Producer<Animal>.
  • in T marks a consumer (contravariant): T may appear only in input positions, and Sink<Animal> is a Sink<Dog>.
  • Function types are in for parameters and out for results.
  • Use-site projections (Array<out T>, MutableList<in T>) apply variance to a single parameter when the class itself must stay invariant; this is Java's PECS in wildcard-free form.
  • Prefer read-only collection parameters (List<T>) in APIs, because they are covariant.

Next: Type Erasure and reified