Generics, Variance and where Clauses

Generics, Variance and where Clauses in Kotlin: A distribution warehouse runs on standardized totes, each stencilled with a label saying exactly what it…

The Analogy: The Warehouse Dispensers and Deposit Hoppers

A distribution warehouse runs on standardized totes, each stencilled with a label saying exactly what it carries. The tote design never changes -- same dimensions, same handles -- but the label pins down its contents so that no one loads bearings into a tote marked for glassware. A Kotlin generic type is that labelled tote: one class or function definition, parameterised by a type that is fixed per use, so the container's shape is shared while its contents stay strictly typed. Some totes carry a rule stamped on the label, such as "contents must be weighable"; that is a type constraint, narrowing the parameter to types that satisfy some bound.

Along one wall run gravity-fed dispensers -- chutes that only let items slide out and never accept anything pushed back up. Because you can only ever receive from such a chute, a dispenser stocked with apples is perfectly safe to use wherever a dispenser of fruit is wanted: whatever slides out is at least a fruit, so every downstream expectation is met. This is covariance, marked out in Kotlin. A producer that only hands values out may be treated as a producer of any supertype, because narrowing what it contains never violates a promise made in terms of the wider type.

Facing them are one-way deposit hoppers -- openings that only accept items and never return them. Here the substitution runs the other way. A hopper rated to accept any fruit can stand in for one that is merely required to accept apples, because a hopper willing to take all fruit will certainly take apples. This is contravariance, marked in. A consumer that only takes values in may be treated as a consumer of any subtype. And when a bin both dispenses and accepts -- a working container you read from and write to -- neither substitution is safe, so it must be invariant, which is exactly the default when you write a bare type parameter with no variance mark.

The mishap that corrupts the inventory is the clerk who grabs a general fruit dispenser, decides to treat it as an apple dispenser, and then tries to drop an orange back into it, expecting only apples to slide out for the next picker. The one-way stencilling exists precisely to forbid this: a covariant out container cannot be written to at all, because a single wrong deposit would let a non-apple into a chute that everyone downstream is relying on to yield apples. Kotlin enforces this at compile time -- a type marked out may not appear in an input position, and one marked in may not appear in an output position -- which is how the language rules out the classic unsound-store bug that untyped containers invite.


Syntax or Core Structure

A generic function or class names its type parameter in angle brackets. A constraint after a colon bounds the parameter to subtypes of some type, which unlocks the members of that bound inside the body.

fun <T : Comparable<T>> maxOf(a: T, b: T): T =
    if (a >= b) a else b

class Box<T>(private val item: T) {
    fun get(): T = item
}

fun main() {
    println(maxOf(3, 8))
    println(maxOf("apple", "pear"))
    val b = Box("sealed")
    println(b.get())
}

Output:

8
pear
sealed

maxOf is generic over T, constrained to Comparable<T>; that bound is what lets the body use >=, which would not compile for an unconstrained T. Called with two Ints it returns 8; called with two Strings it compares lexicographically and returns "pear" because "pear" sorts after "apple". Box<T> is a generic class holding one item of the parameter type; Box("sealed") infers T as String, and get() returns it. The type parameter is inferred at the call site, so you rarely write it explicitly.


Technical Depth: Variance and Multiple Bounds

The variance marks

Variance decides when Container<Sub> may be used where Container<Super> is expected. The table fixes the three cases.

MarkNameT may appear asSubstitution
out Tcovariantoutput only (return)C<Sub> is a C<Super>
in Tcontravariantinput only (parameter)C<Super> is a C<Sub>
Tinvariantinput and outputno substitution

The rule that makes this sound is positional: a type marked out can only be produced, never consumed, and one marked in can only be consumed, never produced. The compiler checks every use of the parameter against its mark.

A covariant producer

Marking a parameter out lets a container of a subtype flow where a container of a supertype is wanted, because the container only ever hands values out.

class Source<out T>(private val value: T) {
    fun produce(): T = value
}

fun main() {
    val ints: Source<Int> = Source(5)
    val nums: Source<Number> = ints    // safe: Source only produces
    println(nums.produce())
}

Output:

5

Source uses T only as a return type, so it is legal to mark it out. That mark makes Source<Int> a subtype of Source<Number>, so the assignment val nums: Source<Number> = ints compiles. Reading nums.produce() yields the stored 5, now seen through the Number type. Had Source tried to accept a T parameter anywhere, the out mark would have been rejected.

A contravariant consumer

Marking a parameter in lets a container of a supertype flow where a container of a subtype is wanted, because the container only ever takes values in.

class Sink<in T> {
    fun consume(item: T): String = "took " + item
}

fun main() {
    val anyNum: Sink<Number> = Sink()
    val ints: Sink<Int> = anyNum       // safe: Sink only consumes
    println(ints.consume(7))
}

Output:

took 7

Sink uses T only as a parameter, so it may be marked in. That makes Sink<Number> a subtype of Sink<Int> -- the reverse direction from covariance -- so a Sink<Number> can be used where a Sink<Int> is required. Feeding it the Int 7 prints "took 7", because a consumer of any Number certainly consumes an Int.

Several bounds with a where clause

When a type parameter must satisfy more than one bound, list them in a where clause after the signature.

interface Named { val name: String }
interface Aged { val age: Int }

fun <T> describe(x: T): String where T : Named, T : Aged =
    x.name + " is " + x.age

class Person(override val name: String, override val age: Int) : Named, Aged

fun main() {
    println(describe(Person("Ada", 36)))
}

Output:

Ada is 36

The where clause requires T to be both Named and Aged, so inside describe the body may read both name and age. Person implements both interfaces and therefore satisfies the constraint, so describe(Person("Ada", 36)) compiles and prints "Ada is 36". A single colon bound handles one requirement; where is how you demand several at once.

reified recovers the erased type

Because erasure normally discards the type argument, a runtime is T check is impossible in an ordinary generic function. An inline fun with a reified parameter is the exception: inlining substitutes the concrete type, so the check works.

inline fun <reified T> countOf(items: List<Any>): Int =
    items.count { it is T }

fun main() {
    val mixed = listOf(1, "a", 2, "b", 3)
    println("ints: " + countOf<Int>(mixed))
    println("strings: " + countOf<String>(mixed))
}

Output:

ints: 3
strings: 2

Marking T as reified in an inline function lets it is T compile and run, because the compiler bakes the actual type into each call site. Over the mixed list, countOf<Int> matches the three integers and countOf<String> matches the two strings. This is the explicit-type escape hatch the erasure flaw in the next section points to: when runtime behaviour must depend on the type argument, reified (or a passed type token) is how you keep it.

Star projection accepts any instantiation for reading

When you need to handle a container regardless of its exact type argument -- and only touch members that do not depend on it -- use a star projection <*>.

class Crate<T>(val contents: List<T>) {
    fun size(): Int = contents.size
}

fun totalItems(crates: List<Crate<*>>): Int =
    crates.sumOf { it.size() }

fun main() {
    val crates: List<Crate<*>> = listOf(
        Crate(listOf(1, 2, 3)),
        Crate(listOf("a", "b"))
    )
    println("crates: " + crates.size)
    println("items: " + totalItems(crates))
}

Output:

crates: 2
items: 5

Crate<*> means "a Crate of some unknown type," which is exactly enough to call size() because that member does not involve the type argument. The list mixes a Crate<Int> and a Crate<String>, yet totalItems sums their sizes to 3 + 2 = 5. What star projection forbids is any operation that would need to know the real type -- you could not, for instance, add a typed element -- which is why it is a read-mostly view over "any instantiation."


Real World Example: Per-Type Instance Counting

A service builds many Request objects parameterised by their payload format, and the team wants a metric: how many Request<Json> versus Request<Xml> were created. The apparent solution is a counter in the generic class's companion object, incremented in init, on the assumption that each type argument gets its own companion and therefore its own count.

class Json
class Xml

class Request<T>(val payload: T) {
    companion object {
        var total = 0       // intended: a separate count per T
    }
    init { total += 1 }
}

fun main() {
    Request(Json())
    Request(Json())
    Request(Xml())
    println("Request.total = " + Request.total)
}

Output:

Request.total = 3

The counting itself is correct: three Request objects are constructed, each init runs once, and total ends at 3. For a single payload type the metric would be exactly what the team wanted, and the code compiles and runs without complaint.

The intent, though, was two separate numbers -- two for Json, one for Xml -- and there is no way to recover them from this design. The output is a single merged 3, with no split by type argument available anywhere.

The genuine design flaw is assuming that Request<Json> and Request<Xml> are different classes with different companions. They are not. Kotlin generics use type erasure: the type argument exists only at compile time and is gone at runtime, so there is exactly one Request class, one companion object, and one total field shared by every instantiation. The companion is per-class, and after erasure the class is just Request. The fix is to make the distinguishing type explicit rather than relying on the erased parameter: pass a type token such as a KClass into the constructor and key a Map<KClass<*>, Int> in the companion by it, or model genuinely distinct kinds as separate non-generic classes. The broader limitation to carry forward is that any logic which needs to branch on a generic type argument at runtime must be given that type explicitly -- through a reified parameter or a token -- because erasure has already discarded it.

Common Mistakes

  1. Expecting type arguments to survive at runtime. Generics are erased, so Request<Json> and Request<Xml> share one class, one companion, and one set of statics. Pass a type token or use reified when runtime type is needed.
  1. Checking is List<String>. The compiler rejects an instance check against an erased type argument; only is List<*> is allowed. There is no way to ask at runtime what a list's element type was.
  1. Marking a parameter out then using it as input. A covariant out T may appear only in output positions. Trying to accept a T parameter in such a class is a compile error, because it would break the substitution guarantee.
  1. Marking a parameter in then returning it. A contravariant in T may appear only in input positions; returning a T from such a class does not compile.
  1. Assuming List<Int> is a List<Number> by default. Substitution only holds when the type declares variance. List is covariant (out E) so it works, but a custom invariant Box<Int> is not a Box<Number>.
  1. Writing to a covariant producer through a star projection. With MutableList<*> you can read as Any? but cannot add anything except null-safe nothing, because the element type is unknown. Star projection is read-mostly.
  1. Forgetting to constrain a parameter you operate on. Using >= or calling a method on an unconstrained T fails to compile. Add a bound like T : Comparable<T> to unlock those operations.
  1. Overusing declaration-site variance. Not every class needs in/out; add them only when substitution is genuinely wanted, and use use-site projections (out T at the call) for one-off needs.
  1. Relying on unchecked casts to fake generic type checks. as List<Int> on a List<Any> compiles with a warning and defers failure to first misuse, often a ClassCastException far from the cast. Validate elements instead.

Best Practices

  • Add type bounds so the body can use the operations it needs, and prefer a single colon bound, escalating to a where clause only for multiple requirements.
  • Mark a type parameter out when the type only produces it and in when it only consumes it, letting callers substitute subtypes and supertypes safely.
  • Leave a parameter invariant (unmarked) when the type both reads and writes it, since neither substitution is sound.
  • Treat type arguments as compile-time only; when runtime behaviour must depend on the type, pass a reified parameter or an explicit type token.
  • Use star projection <*> when you need to accept any instantiation for reading, and remember it forbids most writes.
  • Prefer use-site variance (a projection at the call site) for a localized need, reserving declaration-site in/out for types whose whole purpose is producing or consuming.
  • Let type inference fill in type arguments at call sites, specifying them explicitly only when inference cannot.
  • Validate element types explicitly rather than leaning on unchecked casts that defer failure to a later, harder-to-trace point.

Practice Exercises

  1. Write a generic fun <T : Comparable<T>> minOf(a: T, b: T): T and call it with both Ints and Strings, confirming the bound lets you use < inside.
  1. Define a covariant Producer<out T> with a single produce(): T and show that a Producer<Int> can be assigned to a Producer<Number>. Then add a method taking a T parameter and observe the compile error.
  1. Reproduce the erasure flaw: put a counter in a generic class's companion, create instances with two different type arguments, and confirm the count is merged. Then redesign it to count per type using a KClass token.
  1. Write a function with two type parameters and a where clause requiring one of them to implement two interfaces, and call it with a class that satisfies both.