Explain declaration-site variance with in and out.
Assesses fundamental understanding of Kotlin conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Variance describes how generic types relate when their type arguments are related. out T (covariant) means Producer<String> can be used where Producer<Any> is expected. in T (contravariant) means Consumer<Any> can be used where Consumer<String> is expected.
interface Producer<out T> { fun produce(): T } // only returns T
interface Consumer<in T> { fun consume(t: T) } // only accepts T
fun feed(c: Consumer<Any>) { c.consume("hi") }
val stringConsumer: Consumer<String> = ...
feed(stringConsumer) // safe: a String consumer handles Any
Kotlin uses declaration-site variance with out and in; Java uses use-site wildcards (? extends, ? super). The safety rule: an out parameter may only appear in return positions, and an in parameter only in parameter positions. Violating this is a compile error, which prevents unsound assignments.
Kotlin also supports use-site projections for individual calls and star projections like List<*> when the type argument is unknown. Understanding variance explains why List is covariant but MutableList is invariant.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.