0
0
Kotlinprogramming~5 mins

In variance (contravariance) in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ACovariance - type used only as output
BInvariant - type used as input and output
CContravariance - type used only as input
DNo variance - type is unrestricted
Which of these is a valid use of a contravariant type parameter in T?
AAs a function parameter type
BAs a function return type
CAs a property type that returns T
DAs a type for a variable that produces T
If Consumer<in T> is contravariant, which assignment is allowed?
AConsumer&lt;Any&gt; = Consumer&lt;String&gt;
BConsumer&lt;String&gt; = Consumer&lt;Any&gt;
CConsumer&lt;String&gt; = Consumer&lt;String&gt;
DConsumer&lt;Any&gt; = Consumer&lt;Any&gt;
Why does Kotlin restrict using contravariant types as return types?
ATo allow more flexible code
BBecause return types must always be invariant
CBecause contravariant types are deprecated
DTo prevent type safety issues
Which keyword would you use to declare a covariant generic type in Kotlin?
Aout
Bin
Cvar
Dval
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.