CodeGym /Courses /Kotlin SELF /Declaration-site variance: out and in in your generic t...

Declaration-site variance: out and in in your generic types

Kotlin SELF
Level 36, Lesson 1
Available

1. Introduction

When you first run into out and in, it is very tempting to think: “Aha, this is some kind of clever magic to make generics work like inheritance”. But it is more correct to think the other way around: out/in is a way to prevent you from doing something unsafe, even if you really want to, even if “I’ll be careful”.

Imagine you are building a small module for our training console application (let it be an expense tracker). We want to write code that will work with Record (a base record), ExpenseRecord (an expense), and IncomeRecord (an income). We already know inheritance, and we want “containers” to adapt as well.

The problem is that containers are different. Some containers are a “box” from which we take out a value. Others are a “bin/receiver” into which we put values. And some are “both”, and that is exactly where invariance and restrictions usually begin.

The key idea of today’s lecture: declaration-site variance (declaration-site variance) is when, in the declaration of your generic type, you honestly tell the compiler: “Look, I will use T only like this”. Kotlin trusts you — and in return allows more flexible subtyping. This is described in the official documentation as declaration-site variance and is shown with the example Source<out T>: if a type really only “gives out” T, you can make it covariant via out.

2. Declaration-site variance: how to declare out/in and what type positions are

Now we will write our own generic types, and it looks almost like “access control”: you are sort of creating an API where dangerous operations are forbidden in advance.

An important point: out and in are written at the point where the type parameter is declared, that is, in the class/interface/function-type header, for example class Box<out T> ... or class Sink<in T> .... This is not a “one-off trick for a single function”, but a rule for the entire type:

  • if T is declared as out, Kotlin will strictly ensure that T is never used as an “input” (in method parameters, setters, etc.);
  • if T is declared as in, Kotlin will ensure you do not try to “expose” a value of type T as an exact type.

Why so strict? Because otherwise variance would break at runtime (just like Java arrays once did, and it still hurts a little). Kotlin prefers: “better not compile than give you a chance to cause a type disaster”.

It is useful to understand how the compiler decides where T is “in” and where it is “out”. In practice, this is about what happens to the value: do you give it out or accept it in?

Below is a small cheat-sheet table. It does not replace understanding, but it helps a lot at the moment when you look at a compiler error and think, “what does it want now?”

Where T appears This T as… Example Allowed with out T Allowed with in T
Function return type out (we expose it)
fun get(): T
yes no
Function parameter in (we accept it)
fun put(x: T)
no yes
val property of type T out (getter)
val current: T
yes no
var property of type T both out and in
var current: T
no no (in the general case)

There is an important “in the general case” here: sometimes you can work around the restriction if you change the design. For example, a consumer can store values as Any?, because Any? does not promise the type T. A producer can accept not T, but something else not related to the type parameter (for example, “reset state”).

3. out T: covariance and a producer

Now we will go through out in practice — this will be the most “intuitive” option, because it is similar to List, which you already know. After that it will be easier to understand in, which usually breaks your brain a bit more at first.

Mini-domain for examples

So the examples are not “about cats and dogs” (although cats and dogs try), let’s make types similar to what might live in our finance tracking application:

open class Record(val id: Int, val comment: String)

class ExpenseRecord(
    id: Int,
    comment: String,
    val amount: Int
) : Record(id, comment)

Here ExpenseRecord is a subtype of Record. So ExpenseRecord can be used where Record is expected (this is ordinary inheritance, which we already had).

A “snapshot” as a producer: Snapshot<out T>

Now let’s create a type that only stores a value and gives it out. This is very similar to a “snapshot of a computation result”, a “server response”, or a “ready value”.

class Snapshot<out T>(private val value: T) {
    fun get(): T = value
}

Note: T is used only in an out position here — it is returned from get(). That is exactly the promise that out requires.

Let’s check subtyping:

fun main() {
    val expenseSnapshot: Snapshot<ExpenseRecord> =
        Snapshot(ExpenseRecord(1, "Coffee", 250))

    val recordSnapshot: Snapshot<Record> = expenseSnapshot

    println(recordSnapshot.get().comment) // Coffee
}

Why is this safe? Because through recordSnapshot we cannot put an “incorrect Record” inside. We can only read, and reading a Record from a Snapshot<ExpenseRecord> is totally fine: an “expense” is also a “record”.

This logic is exactly why Kotlin’s read-only collections are covariant (they are “sources of values”). The documentation explicitly notes that read-only collections are covariant.

What out forbids: you cannot accept T as input

Now let’s try to “improve” Snapshot: add a method set(newValue: T) so that the value can be changed.

class Snapshot<out T>(private var value: T) {
    fun get(): T = value

    // Not allowed — idea example, does not compile:
    // fun set(newValue: T) { value = newValue }
}

Kotlin will forbid this (and that is good). The logic is: if Snapshot<ExpenseRecord> can be assigned to Snapshot<Record>, and then through a variable of type Snapshot<Record> you could call set(Record(...)), then you would put a “plain Record” inside an object that actually stores an ExpenseRecord. Type safety would collapse.

So out is the price of flexibility: you get “liftability” along the type hierarchy, but you lose the ability to safely accept T as input.

Trap: var almost always breaks out

One of the most common surprises for beginners: you declared out T, and then you made a property var value: T and suddenly the compiler is unhappy. The reason is that var is both a getter and a setter. The getter returns T (out position), the setter accepts T (in position). But out requires that T is used only as out.

Look at this idea example:

// Does not compile — shown as a trap:
// class Box<out T>(var value: T)

If you need a “producer”, usually make it a val (read-only) or hide the storage inside and expose it via methods.

4. in T: contravariance and a consumer

If out usually feels “logical”, in often feels at first like “the compiler is messing with you”. Let’s understand it so the compiler looks not like a villain, but like a bouncer at the type-safety club.

The consumer idea: we only accept T

Let’s make a type that accepts values of T, but does not give anything of type T out.

For example, a “formatter” (it takes an object and turns it into a string). This is very practical for our console application: we print things all the time.

class Formatter<in T>(private val toText: (T) -> String) {
    fun format(value: T): String = toText(value)
}

Note: T appears in the parameter format(value: T) — this is an in position. And T also appears as the input of the function type (T) -> String, and a function input also behaves like “in”.

Why subtyping “reverses”

Now the most interesting part: what is a subtype of what?

If ExpenseRecord is a subtype of Record, then Formatter<Record> is a subtype of Formatter<ExpenseRecord>, because Formatter is a consumer (contravariant).

Sounds strange, but the logic is simple: if an object can format any Record, then it can definitely format an ExpenseRecord (because an expense is a special case of a record).

fun main() {
    val recordFormatter: Formatter<Record> =
        Formatter { r -> "#${r.id}: ${r.comment}" }

    val expenseFormatter: Formatter<ExpenseRecord> = recordFormatter

    val e = ExpenseRecord(10, "Taxi", 900)
    println(expenseFormatter.format(e)) // #10: Taxi
}

We did the assignment “in the opposite direction” compared to out. And that is normal: for a consumer everything is mirrored.

What in forbids: you cannot expose T as an exact output type

Let’s try to build a consumer that also “stores the last accepted element” and returns it:

class Sink<in T> {
    // Idea that will not compile if you try to return T:
    // private var last: T? = null
    // fun put(x: T) { last = x }
    // fun last(): T? = last
}

Why not? Because if you have a Sink<Record> and assign it to a variable Sink<ExpenseRecord> (which is allowed with in), then someone will start thinking that last() returns an ExpenseRecord?. But the real object is a Sink<Record> — you could have put any Record there, not necessarily an expense.

So Kotlin allows consumer types to accept T, but does not allow them to “promise” an exact T as output.

5. Where you have already seen out/in in Kotlin

A nice part: you have already used variances, just without noticing. Kotlin tries to make the “correct” variance built into the standard library, so you do not have to write out/in manually all the time.

List<out T> as a read-only producer

Read-only List is covariant, so List<ExpenseRecord> can be used as List<Record>. This is exactly the producer logic we discussed above. In the documentation it is phrased like this: read-only collections are covariant.

Comparable<in T> as a consumer

In Comparable, the type parameter is contravariant: Comparable<in T>. In the documentation, the example is that Comparable<Number> can be assigned to Comparable<Double>, because an object that can compare Number can also compare Double.

Even if you do not want to dive deep into the math of comparisons yet, it is useful to remember the shape: the compared type appears as an input in compareTo(other: T), so it is a consumer → in.

Function types: input is in, output is out

The function type (A) -> B is a very visual model of variances: a function consumes an argument of type A and produces a result of type B. So the input behaves like in, and the output behaves like out.

A practical thought: if you have a function that can accept a Record, then it can automatically accept an ExpenseRecord as well (because an expense is a record). So such a function can be used where an expense handler is expected:

fun main() {
    val handleRecord: (Record) -> String = { r -> "Handled: ${r.comment}" }
    val handleExpense: (ExpenseRecord) -> String = handleRecord

    println(handleExpense(ExpenseRecord(7, "Lunch", 600))) // Handled: Lunch
}

If you just thought “this looks like an example from the previous lecture” — yes. Now you can see it is not an accident: it is the same consumer/producer principle, just in the shape of functions.

6. Practical refactoring: a data source and an output handler

So today’s topic does not stay “in a vacuum”, let’s carefully integrate it into the console app logic. We are not going to build “architecture for decades” (that is a separate discipline), but we will do one small, clear thing: separate data retrieval from output formatting via out/in.

Producer of report data: ReportSource<out T>

Let’s make a source that yields items for a report. It is a producer, so out.

class ReportSource<out T>(private val items: List<T>) {
    fun firstOrNull(): T? = items.firstOrNull()
}

Use it:

fun main() {
    val expenses = listOf(
        ExpenseRecord(1, "Coffee", 250),
        ExpenseRecord(2, "Book", 1200)
    )

    val expenseSource: ReportSource<ExpenseRecord> = ReportSource(expenses)
    val recordSource: ReportSource<Record> = expenseSource

    println(recordSource.firstOrNull()?.comment) // Coffee
}

Everything is logical here: a source of expenses can be used as a source of records because it only “gives out”.

Output consumer: Printer<in T>

Now let’s make a “printing” object that accepts T and prints to the console. It is a consumer, so in.

class Printer<in T>(private val toLine: (T) -> String) {
    fun print(value: T) {
        println(toLine(value))
    }
}

And check type substitution:

fun main() {
    val printRecord = Printer<Record> { r -> "Record: ${r.comment}" }
    val printExpense: Printer<ExpenseRecord> = printRecord

    printExpense.print(ExpenseRecord(3, "Taxi", 900)) // Record: Taxi
}

An object that can print “any Record” fits where we need to print “only ExpenseRecord”. That is contravariance with in.

Connecting producer and consumer in one function

Now we can write a function that takes a “source” and a “printer” and prints the first item. It is useful to see how out and in start working together in one place:

fun printFirst(
    source: ReportSource<Record>,
    printer: Printer<Record>
) {
    val first = source.firstOrNull()
    if (first != null) {
        printer.print(first)
    }
}

Now use it by substituting “more specific” and “more general” things where it is safe:

fun main() {
    val expenses = listOf(ExpenseRecord(1, "Coffee", 250))

    val sourceExpenses = ReportSource(expenses)             // ReportSource<ExpenseRecord>
    val printerRecords = Printer<Record> { "-> ${it.comment}" }

    printFirst(sourceExpenses, printerRecords)              // -> Coffee
}

Why does this even compile if printFirst expects ReportSource<Record>, but we provide a ReportSource<ExpenseRecord>? Because ReportSource is declared with out, meaning it is covariant. Why does the printer compile? Because Printer is declared with in, meaning it is contravariant.

7. Common mistakes when designing with out and in

Mistake #1: using out and then trying to build a “normal mutable container”.
A very common situation: you write class Box<out T> and then add fun set(x: T) or make a var value: T. The compiler complains, and it feels like it is “ruining your life”. In reality it protects you from a logical hole: a covariant type cannot be safely used as a receiver of T. If you need mutability, either make the type invariant (class Box<T>), or split the roles into producer and consumer with separate types.

Mistake #2: using in and then trying to return T as output.
With a consumer type, you often want to “return the last accepted element”. But as soon as the type becomes contravariant, returning T becomes an unsafe promise: from the outside, people will expect a more specific type than what could actually have been stored inside. In such cases, either return something more general (Any?) or change the design: a consumer does not have to be able to “take out” what it accepted.

Mistake #3: thinking out makes an object immutable.
out does not mean “immutable”. It means “in my API, the type parameter is used only as an output”. You can absolutely have methods without T that change internal state (for example, clear()), and the type will still be covariant. Variance guarantees only type safety, not the absence of mutation — these are different concepts.

Mistake #4: trying to pick out or in “at random” just to make it compile.
out and in are not “medicine for type errors”; they describe meaning. A good way to stop guessing is to say it out loud every time: does my type produce T or consume T? If it produces (read, get, return) — out. If it consumes (accept, add, process input) — in. If it does both — most likely it is invariant and you will have to design it differently.

Mistake #5: being surprised that var breaks both out and in.
A var property x: T both gives out T (getter) and accepts T (setter). So in a type with out T it is forbidden because of the setter, and in a type with in T it is forbidden because of the getter. If you want to store a value but keep variance, it usually helps to: for out use val, and for in store not T internally but a more general type (Any?) or not store it at all (make a “pure handler”).

1
Task
Kotlin SELF, level 36, lesson 1
Locked
Record snapshot
Record snapshot
1
Task
Kotlin SELF, level 36, lesson 1
Locked
Report formatter
Report formatter
1
Task
Kotlin SELF, level 36, lesson 1
Locked
Read-only box
Read-only box
1
Task
Kotlin SELF, level 36, lesson 1
Locked
String Accumulator
String Accumulator
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION