Recall & Review
beginner
What does
in keyword mean in Kotlin generics?The
in keyword marks a generic type as contravariant. It means the type can only be used as input (consumer) and not as output (producer).Click to reveal answer
beginner
Explain contravariance with a real-life example.
Imagine a mail sorter who can accept any type of mail but never sends mail. Contravariance means you can use a sorter for a more general mail type when a more specific one is expected.
Click to reveal answer
intermediate
How does Kotlin enforce contravariance in function parameters?
Kotlin allows contravariance on generic types used only as function parameters (inputs) by marking them with <code>in</code>. This prevents returning that type from the function.Click to reveal answer
intermediate
What happens if you try to use a contravariant type as a return type in Kotlin?
Kotlin will give a compile-time error because contravariant types (marked with
in) cannot be used as output types to keep type safety.Click to reveal answer
beginner
Show a simple Kotlin example of contravariance using
in keyword.interface Consumer<in T> {
fun consume(item: T)
}
// Consumer<Any> can be used where Consumer<String> is expected because of contravariance.
Click to reveal answer
What does the
in keyword indicate in Kotlin generics?✗ Incorrect
The
in keyword marks a generic type as contravariant, meaning it can only be used as input.Which of these is a valid use of a contravariant type parameter
in T?✗ Incorrect
Contravariant types can only be used as input parameters, not as return types or producers.
If
Consumer<in T> is contravariant, which assignment is allowed?✗ Incorrect
Contravariance allows assigning a consumer of a more general type (Any) to a consumer of a more specific type (String).
Why does Kotlin restrict using contravariant types as return types?
✗ Incorrect
Using contravariant types as return types can break type safety, so Kotlin forbids it.
Which keyword would you use to declare a covariant generic type in Kotlin?
✗ Incorrect
The
out keyword marks a type as covariant, meaning it can only be used as output.Describe what contravariance means in Kotlin generics and give a simple example.
Think about how a type can be used only as input.
You got /3 concepts.
Explain why Kotlin restricts contravariant types from being used as return types.
Consider what could go wrong if a contravariant type was returned.
You got /3 concepts.