Kotlin Hard technical 1 views 1 min read

Explain declaration-site variance with in and out.

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Kotlin conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

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

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?