Complete the code to declare a contravariant generic interface using the correct keyword.
interface Consumer<[1] T> {
fun consume(item: T)
}In Kotlin, in is used to declare contravariance, allowing the generic type to be used only as input.
Complete the function parameter type to accept a contravariant generic Consumer.
fun feed(consumer: Consumer<[1] Animal>) {
consumer.consume(Dog())
}The in keyword allows the Consumer to accept subtypes of Animal, enabling contravariance.
Fix the error in the function call by adding the correct variance modifier.
val consumer: Consumer<[1] Dog> = object : Consumer<Animal> { override fun consume(item: Animal) { println("Consumed: $item") } }
Declaring Consumer allows assigning a Consumer to it because of contravariance.
Complete the code to create a contravariant function type parameter and call it correctly.
fun process(consumer: ([1] String) -> Unit) { consumer("Hello") } process -> { println(it) }
The function parameter uses in for contravariance on input type, and the arrow -> separates parameter and return type.
Fill all three blanks to declare a contravariant generic class, implement it, and use it.
class Printer<[1] T> { fun print(item: T) { println(item) } } val printer: Printer<[2] Any> = Printer<[3] String>()
Using in declares contravariance, allowing Printer to be assigned to Printer.