Generics and variance basics

Learn Kotlin generics, variance, and type erasure to master Flow signatures and avoid runtime crashes in Android development and technical interviews. About 22 minutes.

Why it matters

  • Variance rules are checked by the compiler, so the runtime crashes come from code that goes around them: casting a List to MutableList, or an unchecked cast of an erased generic type. These fail far from the line that caused them.
  • Interviewers at senior level ask you to justify why a type is out, in, or invariant, and to explain what happens at the JVM level after erasure.
  • Coroutine types like Flow<out T> and StateFlow<out T> are declared covariant, while MutableStateFlow<T> is invariant. Reading those signatures correctly explains which assignments compile in ViewModels and repositories.
  • Reified type parameters let you write is T and T::class inside a generic function without passing a Class object; forgetting the inline + reified pair is a common compile error in utility code.

The simple explanation

  • A covariant type (out) is a fruit vending machine: you only take things out, so a machine that gives apples can stand in for a machine that gives fruit.
  • A contravariant type (in) is a recycling bin: you only put things in, so a bin that accepts any fruit can stand in for a bin for apples.
  • An invariant container is a fruit bowl you both take from and add to: a bowl of apples cannot stand in for a bowl of fruit, because someone could add a banana.
  • Star projection is a locked display case: you can look at the items but cannot put anything new in.
  • Type erasure is like removing the label from a box at the factory: at runtime the box just says 'box', not 'box of apples'.

Kotlin generics use variance to control how subtypes relate through generic types. Three modes exist:

VarianceKeywordSubstitution ruleStdlib example
Covariantout TFoo<String> is a subtype of Foo<Any>List<out E>, Sequence<out T>, Flow<out T>
Contravariantin TFoo<Any> is a subtype of Foo<String>the parameter of a function type: (Any) -> Unit is a subtype of (String) -> Unit
Invariant(none)No substitution allowedMutableList<E>, Array<T>

Covariance (out): the type parameter appears only in output positions (return types) of non-private members. A Producer<out T> can produce T but never consume it, so Producer<String> is safely usable where Producer<Any> is expected.

Contravariance (in): the type parameter appears only in input positions (parameters). A Consumer<in T> can consume T but never produce it, so Consumer<Any> is safely usable where Consumer<String> is expected.

Invariant (no keyword): the type appears in both positions. MutableList<T> has get(): T (output) and add(T) (input), so it cannot be either. MutableList<String> is not a subtype of MutableList<Any>.

Use-site variance: you can also add out or in where a type is used, like Java wildcards. The stdlib's sortedWith(comparator: Comparator<in T>) accepts a Comparator<Any> for a List<String>.

Star projection (Foo<*>) means "some type argument I do not know". For MutableList<*> you can read elements as Any? but cannot add anything, because the compiler does not know which type is safe to add.

Type erasure: at runtime, List<String> and List<Int> are both java.util.List. The JVM does not store the type argument in the object. This is why item is T does not compile for a normal type parameter. The reified keyword (only on inline functions) makes the compiler insert the actual type at every call site, enabling is T and T::class.

Notes

  • out T (covariant) means T appears only in return positions. List<out E> is the canonical example. You can read but not write.
  • in T (contravariant) means T appears only in parameter positions. Function type parameters are the canonical example. You can write but not read.
  • No keyword means invariant. MutableList<T> is invariant because it has both get(): T and add(T). Array<T> is also invariant, unlike Java arrays.
  • MutableList<*> lets you call size, get() (returning Any?) and forEach, but not add().
  • Type erasure: at the JVM level, List<String> and List<Int> are both java.util.List. That is why x is List<String> does not compile; you write x is List<*>.
  • reified works only on inline functions. The compiler copies the function body into each call site with the real type, enabling is T and T::class. Reified functions cannot be called from Java.
  • You cannot declare class Foo<out T> if T appears as a parameter type of a non-private member. The compiler rejects it.
  • You cannot declare class Foo<in T> if T appears as a return type of a non-private member. The compiler rejects it.
  • kotlin.Comparator on the JVM is java.util.Comparator, which is invariant. Stdlib functions add in at the use site, Comparator<in T>, which is Java's PECS rule ("producer extends, consumer super") made explicit.
  • Never cast a List to MutableList to add items. If you need a mutable copy, call toMutableList().

Code example

This code shows a small data pipeline with a covariant Producer, a contravariant Consumer, an invariant MutableList, and a star-projected list. Each section is labelled so you can see which variance rule applies.

// Variance in a data pipeline
 
// Covariant: Producer<String> IS a Producer<Any>
interface Producer<out T> {
    fun produce(): T
}
 
// Contravariant: Consumer<Any> IS a Consumer<String>
interface Consumer<in T> {
    fun consume(item: T)
}
 
class JsonProducer : Producer<String> {
    override fun produce(): String = "{\"id\":1}"
}
 
class LogConsumer : Consumer<Any> {
    override fun consume(item: Any) {
        println("Logged: " + item)
    }
}
 
// Invariant: MutableList<String> is NOT a MutableList<Any>
fun process(items: MutableList<String>) {
    items.add("new") // safe: only String enters
}
 
fun main() {
    // Covariance: subtype producer assigned to supertype slot
    val p: Producer<Any> = JsonProducer()
    println(p.produce())
 
    // Contravariance: supertype consumer assigned to subtype slot
    val c: Consumer<String> = LogConsumer()
    c.consume("hello")
 
    // Star projection: read as Any?, cannot add
    val list: MutableList<*> = mutableListOf(1, 2, 3)
    println("Size: " + list.size + ", first: " + list[0])
    // list.add(4) // COMPILE ERROR: the element type is unknown
}
  • Producer<out T> is valid because T only appears in the return position of produce(). Adding a parameter of type T would be a compile error.
  • Consumer<in T> is valid because T only appears in the parameter position of consume(). Returning T would be a compile error.
  • MutableList<*> hides the element type: reading gives Any?, and the commented-out list.add(4) would not compile.

Run the idea in plain Kotlin

interface Producer<out T> {
  fun produce(): T
}

interface Consumer<in T> {
  fun consume(item: T)
}

class IntProducer : Producer<Int> {
  override fun produce(): Int = 42
}

class AnyConsumer : Consumer<Any> {
  override fun consume(item: Any) {
      println("Consumed: " + item)
  }
}

inline fun <reified T> List<*>.findFirstOfType(): T? {
  for (item in this) {
      if (item is T) return item
  }
  return null
}

fun main() {
  // Covariance: Producer<Int> is a Producer<Any>
  val p: Producer<Any> = IntProducer()
  println("Produced: " + p.produce())

  // Contravariance: Consumer<Any> is a Consumer<Int>
  val c: Consumer<Int> = AnyConsumer()
  c.consume(10)

  // Star projection: read as Any?, cannot add
  val nums: MutableList<*> = mutableListOf(1, 2, 3)
  println("Star list size: " + nums.size)
  // nums.add(4) // would not compile

  // Reified type parameter with is T check
  val mixed = listOf(1, "two", 3.0)
  val firstStr = mixed.findFirstOfType<String>()
  println("First String: " + firstStr)
  val firstInt = mixed.findFirstOfType<Int>()
  println("First Int: " + firstInt)
}

The playground prints Produced: 42, Consumed: 10, Star list size: 3, First String: two and First Int: 1.

In production

Casting a read-only list to add an item
  • A repository returned List<Entity>. To add an optimistic item, a ViewModel wrote (repo.items() as MutableList<Entity>).add(draft).
  • On the normal path the list came from .map { }, which returns an ArrayList, so the cast and add() worked.
  • On the empty path the repository returned emptyList(), a read-only singleton. Users with no items crashed with UnsupportedOperationException when they created their first one.
  • The unit tests always started with sample data, so they never hit the empty path.
The fix
  • Reproduce with a unit test where the repository returns no items. It crashes before the fix.
  • Replace the cast with a copy: val updated = repo.items() + draft, or toMutableList() when several changes are needed.
  • Review rule: never cast List to MutableList. A read-only type is a promise the caller should not break.
Unchecked cast after JSON parsing
  • A cache parsed stored JSON with Gson: gson.fromJson(json, List::class.java) as List<User>. The cast compiled with an unchecked-cast warning.
  • Because of erasure, Gson did not know the element type and built a list of LinkedTreeMap objects. The cast to List<User> succeeded, since at runtime it only checks for List.
  • The crash came later, on users.first().name, as a ClassCastException ("LinkedTreeMap cannot be cast to User") in a screen far from the parsing code.
The fix
  • Reproduce with a unit test that parses a sample JSON string and reads a field from the first element. It fails before the fix.
  • Pass the full generic type: object : TypeToken<List<User>>() {}.type, or a small inline fun <reified T> Gson.fromJson(json: String): T helper that builds the TypeToken from T.
  • Treat unchecked-cast warnings as errors in data code. An unchecked cast on a generic type is not checked at runtime.

Common mistakes

  • Casting List<T> to MutableList and calling add(). The cast compiles because both are java.util.List at runtime, but the object may be read-only (for example emptyList() or listOf()), so add() throws UnsupportedOperationException. Create a copy with toMutableList() when you need to mutate.
  • Declaring out T on a type that has T as a parameter. The compiler rejects it. If Box<String> could be used as Box<Any>, a method that takes T would accept an Int into a box of strings. Remove out or redesign the interface.
  • Assuming MutableList<String> is a subtype of MutableList<Any>. MutableList is invariant. If it were allowed, you could add an Int through the MutableList<Any> reference into a list of strings. The compiler blocks this substitution.
  • Using is T inside a generic function without reified. It does not compile: "Cannot check for instance of erased type". Make the function inline with a reified T, or pass a KClass<T> and use isInstance.
  • Using in T on a type that returns T. The compiler rejects it. If Sink<Any> could be used as Sink<String>, a method returning T would hand a caller expecting a String something that may be an Int.
  • Trusting an unchecked cast on a generic type. value as List<User> only checks that the value is a List. The element type is never checked, so the failure appears later, wherever an element is used.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between covariant and contravariant generics in Kotlin?”

“What is star projection and when do you use it?”

“What is type erasure and how does reified help?”

“Why is MutableList<T> invariant?”

Quiz

Which variance makes List<String> a subtype of List<Any>?

What can you do with a value of type MutableList<*>?

What is required to use 'is T' inside a generic function body?

Which of these standard types is invariant in its element type?

0 of 4 answered

Mini task

Add variance to a generic pipeline (15 min)

  1. Create an interface Transformer<in Input, out Output> with a single method fun transform(input: Input): Output.
  2. Implement StringToIntTransformer that implements Transformer<String, Int> and returns input.length.
  3. Write a function runPipeline(transformer: Transformer<String, *>, input: String): Any? that calls transformer.transform(input) and returns the result. The star hides the output type, so the result is Any?.
  4. In main(), assign StringToIntTransformer() to a variable of type Transformer<String, Any> and confirm the compiler accepts it (covariant output). Then try Transformer<Any, Int> and confirm it is rejected (a transformer of strings cannot accept any input).
  5. Try adding a method fun accept(item: Output) to the interface. Observe the compile error: an out type parameter cannot appear in a parameter position. Remove the method.
  6. Try adding a method fun lastInput(): Input. Observe the compile error: an in type parameter cannot appear in a return position. Remove the method.

Done condition: The pipeline compiles and runs, printing the length of a string. The two failed additions (step 5 and step 6) and the rejected assignment in step 4 produce compiler errors that you can explain in one sentence each.

Next: Android Studio project structure