0
0
Kotlinprogramming~10 mins

In variance (contravariance) in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a contravariant generic interface using the correct keyword.

Kotlin
interface Consumer<[1] T> {
    fun consume(item: T)
}
Drag options to blanks, or click blank then click option'
Avar
Bin
Cout
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'out' instead of 'in' for contravariance.
Using 'var' or 'val' which are not variance keywords.
2fill in blank
medium

Complete the function parameter type to accept a contravariant generic Consumer.

Kotlin
fun feed(consumer: Consumer<[1] Animal>) {
    consumer.consume(Dog())
}
Drag options to blanks, or click blank then click option'
Ain
Bout
Cvar
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'out' which is for covariance, not contravariance.
Omitting the variance keyword causing type errors.
3fill in blank
hard

Fix the error in the function call by adding the correct variance modifier.

Kotlin
val consumer: Consumer<[1] Dog> = object : Consumer<Animal> {
    override fun consume(item: Animal) {
        println("Consumed: $item")
    }
}
Drag options to blanks, or click blank then click option'
Ain
Bout
Cvar
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'out' which causes type mismatch.
Not using any variance modifier causing compilation error.
4fill in blank
hard

Complete the code to create a contravariant function type parameter and call it correctly.

Kotlin
fun process(consumer: ([1] String) -> Unit) {
    consumer("Hello")
}

process -> { println(it) }
Drag options to blanks, or click blank then click option'
Ain
Bout
C->
D->>
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'out' instead of 'in' for the input parameter.
Using '->>' which is invalid syntax.
5fill in blank
hard

Fill all three blanks to declare a contravariant generic class, implement it, and use it.

Kotlin
class Printer<[1] T> {
    fun print(item: T) {
        println(item)
    }
}

val printer: Printer<[2] Any> = Printer<[3] String>()
Drag options to blanks, or click blank then click option'
Ain
Bout
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'out' which is covariance, not contravariance.
Mixing variance modifiers causing type mismatch.