Bird
Raised Fist0
Kotlinprogramming~20 mins

Out variance (covariance) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Covariance Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using out variance?
Consider the following Kotlin code that uses out variance in a generic interface. What will be printed when running the main function?
Kotlin
interface Producer<out T> {
    fun produce(): T
}

class StringProducer : Producer<String> {
    override fun produce(): String = "Hello"
}

fun printProduced(producer: Producer<Any>) {
    println(producer.produce())
}

fun main() {
    val stringProducer: Producer<String> = StringProducer()
    printProduced(stringProducer)
}
AHello
BPrints null
CRuntime exception
DCompilation error due to type mismatch
Attempts:
2 left
💡 Hint
Remember that out variance allows a subtype to be used where a supertype is expected.
🧠 Conceptual
intermediate
2:00remaining
Why does Kotlin allow Producer to be assigned to Producer when out is used?
Choose the best explanation for why Kotlin permits this assignment when out variance is declared.
ABecause <code>out</code> means the generic type is only produced (returned), so it is safe to treat a <code>Producer<String></code> as a <code>Producer<Any></code>.
BBecause Kotlin ignores generic types at runtime, so all assignments are allowed.
CBecause <code>out</code> means the generic type can be both produced and consumed, allowing any assignment.
DBecause <code>Producer<String></code> and <code>Producer<Any></code> are unrelated types and Kotlin allows unsafe casts automatically.
Attempts:
2 left
💡 Hint
Think about what out means for how the generic type is used inside the interface.
🔧 Debug
advanced
2:00remaining
What error does this Kotlin code produce?
Examine the code below. What error will the Kotlin compiler report?
Kotlin
interface Consumer<in T> {
    fun consume(item: T)
}

fun acceptConsumer(consumer: Consumer<Any>) {}

fun main() {
    val stringConsumer: Consumer<String> = object : Consumer<String> {
        override fun consume(item: String) {
            println(item)
        }
    }
    acceptConsumer(stringConsumer)
}
ARuntime exception due to type cast
BNo error, code compiles and runs printing the item
CType mismatch: inferred type is Consumer<String> but Consumer<Any> was expected
DSyntax error: missing override keyword
Attempts:
2 left
💡 Hint
Consider how in variance affects assignment compatibility.
❓ Predict Output
advanced
2:00remaining
What is the output of this Kotlin code with mixed variance?
Given the following Kotlin code, what will be printed when main runs?
Kotlin
interface Box<out T> {
    fun get(): T
}

class IntBox(private val value: Int) : Box<Int> {
    override fun get(): Int = value
}

fun printBox(box: Box<Number>) {
    println(box.get())
}

fun main() {
    val intBox: Box<Int> = IntBox(42)
    printBox(intBox)
}
APrints null
B42
CCompilation error due to type mismatch
DRuntime exception
Attempts:
2 left
💡 Hint
Remember that out variance allows a subtype to be used where a supertype is expected.
🧠 Conceptual
expert
2:00remaining
Why can't you use out variance on a generic type parameter if the type is consumed as a function parameter?
Select the best reason why Kotlin forbids declaring a generic type parameter as out if it is used as a function parameter type inside the interface or class.
ABecause function parameters are always covariant regardless of variance annotations.
BBecause Kotlin requires all generic parameters to be invariant if used in functions.
CBecause <code>out</code> variance only applies to classes, not interfaces.
DBecause <code>out</code> means the type can only be produced (returned), so using it as a function parameter (consumed) breaks type safety.
Attempts:
2 left
💡 Hint
Think about what out means and how function parameters use types.

Practice

(1/5)
1. What does the out keyword mean in Kotlin generics?
easy
A. The generic type can be used for both input and output.
B. The generic type is used only for input (consuming values).
C. The generic type is used only for output (producing values).
D. The generic type is mutable and can be changed.

Solution

  1. Step 1: Understand the meaning of out in Kotlin generics

    The out keyword means the generic type is only used to produce values, not consume them.
  2. Step 2: Compare options with this meaning

    The generic type is used only for output (producing values). correctly states that the generic type is used only for output (producing values). Other options describe input or mutability, which are incorrect.
  3. Final Answer:

    The generic type is used only for output (producing values). -> Option C
  4. Quick Check:

    Out variance = output only [OK]
Hint: Remember: out means output only, no input allowed [OK]
Common Mistakes:
  • Confusing out with in variance (input)
  • Thinking out allows mutation
  • Assuming out means both input and output
2. Which of the following is the correct syntax to declare a covariant generic interface in Kotlin?
easy
A. interface Producer { fun produce(): T }
B. interface Producer { fun produce(): T }
C. interface Producer<T> { fun produce(input: T) }
D. interface Producer<T> { fun produce(): T }

Solution

  1. Step 1: Identify covariance syntax in Kotlin

    Covariance is declared using out before the generic type parameter, like out T.
  2. Step 2: Match syntax with options

    interface Producer { fun produce(): T } correctly uses out T and a function that returns T. Other options either use in or lack the out keyword.
  3. Final Answer:

    interface Producer<out T> { fun produce(): T } -> Option A
  4. Quick Check:

    Covariant syntax = out T [OK]
Hint: Covariant generics use 'out' before the type parameter [OK]
Common Mistakes:
  • Using 'in' instead of 'out' for covariance
  • Omitting 'out' keyword
  • Confusing input and output functions
3. What will be the output of the following Kotlin code?
interface Source {
    fun next(): T
}

class StringSource : Source<String> {
    override fun next() = "Hello"
}

fun printSource(source: Source<Any>) {
    println(source.next())
}

fun main() {
    val stringSource = StringSource()
    printSource(stringSource)
}
medium
A. Hello
B. Compilation error due to type mismatch
C. Runtime error
D. Prints null

Solution

  1. Step 1: Understand covariance in the interface

    The interface Source is declared with out T, so Source<String> can be used where Source<Any> is expected.
  2. Step 2: Trace the function call and output

    stringSource returns "Hello" from next(). Passing it to printSource works due to covariance, so it prints "Hello".
  3. Final Answer:

    Hello -> Option A
  4. Quick Check:

    Covariance allows subtype substitution = Hello [OK]
Hint: Covariance lets Source<String> be used as Source<Any> safely [OK]
Common Mistakes:
  • Expecting a compilation error due to type mismatch
  • Confusing covariance with invariance
  • Thinking runtime error occurs
4. Identify the error in this Kotlin code using out variance:
interface Producer {
    fun produce(input: T): T
}
medium
A. No error, code is correct
B. Missing return type in function produce
C. Interface must be declared with in instead of out
D. Cannot use T as a function parameter when declared with out

Solution

  1. Step 1: Check usage of generic type T with out variance

    When T is declared with out, it can only be used as a return type, not as a function parameter.
  2. Step 2: Analyze the function signature

    The function produce(input: T): T uses T as a parameter, which is not allowed with out T.
  3. Final Answer:

    Cannot use T as a function parameter when declared with out -> Option D
  4. Quick Check:

    Out variance forbids T as input parameter [OK]
Hint: Out means T only as output, not input parameters [OK]
Common Mistakes:
  • Ignoring variance rules for function parameters
  • Thinking out allows input parameters
  • Confusing in and out variance
5. Given the following Kotlin classes:
open class Animal
class Dog : Animal()

interface Producer {
    fun produce(): T
}

fun feedAnimals(producer: Producer<Animal>) {
    val animal = producer.produce()
    println("Feeding an animal")
}

fun main() {
    val dogProducer: Producer<Dog> = object : Producer<Dog> {
        override fun produce() = Dog()
    }
    feedAnimals(dogProducer)
}

Why does this code compile and run without errors?
hard
A. Because Kotlin ignores variance annotations at runtime
B. Because Producer is covariant with out, allowing Producer<Dog> where Producer<Animal> is expected
C. Because produce() returns a generic type without restrictions
D. Because Dog is a superclass of Animal, so substitution is allowed

Solution

  1. Step 1: Understand covariance with out keyword

    The interface Producer is declared with out T, making it covariant. This means Producer<Dog> can be used where Producer<Animal> is expected.
  2. Step 2: Analyze class hierarchy and function call

    Dog is a subtype of Animal. The function feedAnimals expects Producer<Animal>, but dogProducer is Producer<Dog>. Covariance allows this substitution safely.
  3. Final Answer:

    Because Producer is covariant with out, allowing Producer<Dog> where Producer<Animal> is expected -> Option B
  4. Quick Check:

    Covariance allows subtype substitution [OK]
Hint: Covariance lets Producer<Dog> be used as Producer<Animal> [OK]
Common Mistakes:
  • Thinking Dog is superclass of Animal
  • Ignoring variance and expecting error
  • Assuming produce() return type is unrestricted
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard