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?✗ Incorrect
out enables covariance, allowing a subtype to be used where a supertype is expected.
Can a covariant generic type parameter be used as a function parameter inside the class/interface?
✗ Incorrect
Covariant type parameters (out) can only be used in output positions, like return types, not as input parameters.
Which of these is a correct example of covariance in Kotlin?
✗ Incorrect
Producer with out T can produce values of type T. Consumer with out T is invalid because it consumes T.
What error will Kotlin show if you try to use a covariant type as a function parameter?
✗ Incorrect
Kotlin shows a variance conflict error because covariant types cannot be used as input parameters.
If
List is declared as interface List, what does this mean?✗ Incorrect
Covariant out T means you can safely read elements of type T but not add them.
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.