Complete the code to declare a covariant interface in Kotlin.
interface Producer<[1] T> {
fun produce(): T
}In Kotlin, out keyword declares covariance, allowing the type to be returned (produced) but not consumed.
Complete the function signature to accept a covariant Producer.
fun <T> consume(producer: Producer<[1] T>) {
val item = producer.produce()
println(item)
}The parameter type uses out to accept a covariant Producer, ensuring safe usage.
Fix the error in the assignment by adding the correct variance modifier.
val stringsProducer: Producer<String> = object : Producer<String> {
override fun produce() = "Hello"
}
val anyProducer: Producer<[1] Any> = stringsProducerUsing out variance allows assigning Producer to Producer safely.
Fill both blanks to create a covariant list producer and consume it safely.
interface ListProducer<[1] T> { fun produceList(): List<T> } fun printFirst(producer: ListProducer<[2] String>) { println(producer.produceList().first()) }
Both blanks use out to declare covariance, allowing safe production and consumption of lists.
Fill all three blanks to define a covariant producer interface, a function consuming it, and a variable assignment.
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
Using out in all three places declares covariance, allowing safe assignment and usage.