Generics and variance basics
Why it matters
- Variance rules are checked by the compiler, so the runtime crashes come from code that goes around them: casting a
ListtoMutableList, 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>andStateFlow<out T>are declared covariant, whileMutableStateFlow<T>is invariant. Reading those signatures correctly explains which assignments compile in ViewModels and repositories. - Reified type parameters let you write
is TandT::classinside a generic function without passing aClassobject; 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:
| Variance | Keyword | Substitution rule | Stdlib example |
|---|---|---|---|
| Covariant | out T | Foo<String> is a subtype of Foo<Any> | List<out E>, Sequence<out T>, Flow<out T> |
| Contravariant | in T | Foo<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 allowed | MutableList<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 bothget(): Tandadd(T).Array<T>is also invariant, unlike Java arrays. MutableList<*>lets you callsize,get()(returningAny?) andforEach, but notadd().- Type erasure: at the JVM level,
List<String>andList<Int>are bothjava.util.List. That is whyx is List<String>does not compile; you writex is List<*>. reifiedworks only oninlinefunctions. The compiler copies the function body into each call site with the real type, enablingis TandT::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.Comparatoron the JVM isjava.util.Comparator, which is invariant. Stdlib functions addinat the use site,Comparator<in T>, which is Java's PECS rule ("producer extends, consumer super") made explicit.- Never cast a
ListtoMutableListto add items. If you need a mutable copy, calltoMutableList().
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 ofproduce(). Adding a parameter of type T would be a compile error.Consumer<in T>is valid because T only appears in the parameter position ofconsume(). Returning T would be a compile error.MutableList<*>hides the element type: reading givesAny?, and the commented-outlist.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
- 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 anArrayList, so the cast andadd()worked. - On the empty path the repository returned
emptyList(), a read-only singleton. Users with no items crashed withUnsupportedOperationExceptionwhen they created their first one. - The unit tests always started with sample data, so they never hit the empty path.
- 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, ortoMutableList()when several changes are needed. - Review rule: never cast
ListtoMutableList. A read-only type is a promise the caller should not break.
- 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
LinkedTreeMapobjects. The cast toList<User>succeeded, since at runtime it only checks forList. - The crash came later, on
users.first().name, as aClassCastException("LinkedTreeMap cannot be cast to User") in a screen far from the parsing code.
- 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 smallinline fun <reified T> Gson.fromJson(json: String): Thelper that builds theTypeTokenfromT. - 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>toMutableListand calling add(). The cast compiles because both arejava.util.Listat runtime, but the object may be read-only (for exampleemptyList()orlistOf()), soadd()throwsUnsupportedOperationException. Create a copy withtoMutableList()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 asBox<Any>, a method that takes T would accept anIntinto a box of strings. Removeoutor redesign the interface. - Assuming MutableList<String> is a subtype of MutableList<Any>. MutableList is invariant. If it were allowed, you could add an
Intthrough theMutableList<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
inlinewith areifiedT, or pass aKClass<T>and useisInstance. - Using in T on a type that returns T. The compiler rejects it. If
Sink<Any>could be used asSink<String>, a method returning T would hand a caller expecting aStringsomething that may be anInt. - Trusting an unchecked cast on a generic type.
value as List<User>only checks that the value is aList. 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)
- Create an interface
Transformer<in Input, out Output>with a single methodfun transform(input: Input): Output. - Implement
StringToIntTransformerthat implementsTransformer<String, Int>and returnsinput.length. - Write a function
runPipeline(transformer: Transformer<String, *>, input: String): Any?that callstransformer.transform(input)and returns the result. The star hides the output type, so the result isAny?. - In
main(), assignStringToIntTransformer()to a variable of typeTransformer<String, Any>and confirm the compiler accepts it (covariant output). Then tryTransformer<Any, Int>and confirm it is rejected (a transformer of strings cannot accept any input). - Try adding a method
fun accept(item: Output)to the interface. Observe the compile error: anouttype parameter cannot appear in a parameter position. Remove the method. - Try adding a method
fun lastInput(): Input. Observe the compile error: anintype 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.