Generics & Variance Interview Questions

KOTLIN › Types & Classes

What do in and out mean on a generic type parameter? Explain covariance and contravariance with an example.

What a strong answer covers: out T means the type only produces T (covariant): List<out Animal> can be a List<Cat>, because reading Cats as Animals is safe. in T means it only consumes T (contravariant): a Comparator<in Cat> can be a Comparator<Animal>, because something that compares any Animal can compare Cats. Mnemonic: producer out, consumer in.

Why is List<String> a subtype of List<Any> in Kotlin, but MutableList<String> is not a subtype of MutableList<Any>?

What a strong answer covers: List is declared List<out E>, read-only, so treating Strings as Any is safe. MutableList is invariant because it both reads and writes: if MutableList<String> were a MutableList<Any>, you could add an Int to it and corrupt the original list. Variance is about what operations are safe.

What is type erasure, and how does reified with inline functions get around it?

What a strong answer covers: Generic type arguments are erased at runtime on the JVM, so you can't do 'is T' or T::class in a normal generic function. An inline function with a reified type parameter is inlined at each call site with the real type substituted, so inline fun <reified T> Gson.fromJson(json: String) can use T::class.java. It only works for inline functions and can't be called from Java.

What is the difference between declaration-site and use-site variance? When would you use a star projection?

What a strong answer covers: Declaration-site variance puts in/out on the class (interface Source<out T>), so every use benefits. Use-site variance (type projection) applies it at one usage, like fun copy(from: Array<out Any>, to: Array<Any>), for invariant classes. Star projection Foo<*> means 'some unknown type': you can read values as Any? but can't write, useful when you don't care about the argument.

Design a generic, type-safe event bus or cache API. Where do variance and generic constraints matter, and what goes wrong at runtime because of erasure?

What a strong answer covers: Key points: listeners are consumers, so they're in-variant; a typed key (Key<T>) lets get<T>(key) return T without casts; bounds like <T : Event> restrict inputs. Because of erasure, a Map<Class<*>, Any> must key by class and do an unchecked cast, and List<String> and List<Int> look identical at runtime, so you can't dispatch on generic arguments without a reified type or type token. A strong answer keeps unchecked casts inside one well-tested place.

Back to Generics & Variance