0
0
Kotlinprogramming~5 mins

Out variance (covariance) in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does out keyword mean in Kotlin generics?
The out keyword means the generic type is covariant. It can only be returned (produced) but not consumed (accepted as input). This ensures type safety when using subtypes.
Click to reveal answer
beginner
Why is covariance useful in Kotlin?
Covariance allows you to use a subtype where a supertype is expected, especially for read-only data. For example, a List<Dog> can be used as a List<Animal> if the list is covariant.
Click to reveal answer
intermediate
Given interface Producer<out T>, can you pass T as a function parameter inside this interface?
No. Because T is declared with out, it can only be returned (produced), not consumed as input parameters. This prevents type errors.
Click to reveal answer
intermediate
How does Kotlin enforce covariance at compile time?
Kotlin restricts usage of the covariant type parameter to only output positions (like return types). If you try to use it as an input parameter, the compiler will show an error.
Click to reveal answer
intermediate
What is the difference between out and in variance in Kotlin?
out means covariance (can only produce values), in means contravariance (can only consume values). They control how generic types relate to subtyping.
Click to reveal answer
What does the out keyword in Kotlin generics allow?
AUsing a subtype where a supertype is expected (covariance)
BUsing a supertype where a subtype is expected (contravariance)
CAllowing both input and output of generic type
DDisabling generics
Can a covariant generic type parameter be used as a function parameter inside the class/interface?
AYes, always
BNo, it can only be returned
COnly if marked with <code>in</code>
DOnly if the function is private
Which of these is a correct example of covariance in Kotlin?
Ainterface Producer<in T> { fun produce(): T }
Binterface Consumer<out T> { fun consume(t: T) }
Cinterface Producer<out T> { fun produce(): T }
Dinterface Consumer<in T> { fun consume(): T }
What error will Kotlin show if you try to use a covariant type as a function parameter?
AVariance conflict error
BType mismatch error
CNull pointer exception
DNo error
If List is declared as interface List, what does this mean?
AYou can add elements of type T to the list
BThe list is mutable
CYou can neither add nor read elements
DYou can only read elements of type T from the list
Explain what 'out variance' (covariance) means in Kotlin generics and why it is useful.
Think about how you can safely use subtypes when returning values.
You got /4 concepts.
    Describe a situation where using 'out' variance in Kotlin prevents type errors.
    Consider a list of animals and dogs.
    You got /3 concepts.