0
0
Kotlinprogramming~10 mins

Out variance (covariance) 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 covariant interface in Kotlin.

Kotlin
interface Producer<[1] T> {
    fun produce(): T
}
Drag options to blanks, or click blank then click option'
Aout
Bin
Cvar
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' instead of 'out' which declares contravariance.
Using 'var' or 'val' which are not variance modifiers.
2fill in blank
medium

Complete the function signature to accept a covariant Producer.

Kotlin
fun <T> consume(producer: Producer<[1] T>) {
    val item = producer.produce()
    println(item)
}
Drag options to blanks, or click blank then click option'
Aout
Bvar
Cin
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' which is for contravariance and not compatible here.
Omitting variance keyword causing type mismatch.
3fill in blank
hard

Fix the error in the assignment by adding the correct variance modifier.

Kotlin
val stringsProducer: Producer<String> = object : Producer<String> {
    override fun produce() = "Hello"
}

val anyProducer: Producer<[1] Any> = stringsProducer
Drag options to blanks, or click blank then click option'
Ain
Bval
Cout
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' which is contravariant and causes type mismatch.
Not using any variance modifier causing compilation error.
4fill in blank
hard

Fill both blanks to create a covariant list producer and consume it safely.

Kotlin
interface ListProducer<[1] T> {
    fun produceList(): List<T>
}

fun printFirst(producer: ListProducer<[2] String>) {
    println(producer.produceList().first())
}
Drag options to blanks, or click blank then click option'
Aout
Bin
Cvar
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' which is for consuming, not producing.
Mixing variance keywords causing type errors.
5fill in blank
hard

Fill all three blanks to define a covariant producer interface, a function consuming it, and a variable assignment.

Kotlin
interface Box<[1] T> {
    fun get(): T
}

fun <T> useBox(box: Box<[2] T>) {
    println(box.get())
}

val stringBox: Box<String> = object : Box<String> {
    override fun get() = "Kotlin"
}

val anyBox: Box<[3] Any> = stringBox
Drag options to blanks, or click blank then click option'
Aout
Bin
Cvar
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' which is for consumers, causing type errors.
Omitting variance causing assignment errors.