Bird
Raised Fist0
Kotlinprogramming~10 mins

Out variance (covariance) in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Out variance (covariance)
Define interface with 'out' modifier
↓
Use interface as return type
↓
Assign subtype instance to supertype variable
↓
Call method returning covariant type
↓
Receive value safely as supertype
↓
End
Shows how 'out' modifier allows safe return of subtype as supertype, enabling covariance.
Execution Sample
Kotlin
interface Producer<out T> {
    fun produce(): T
}

open class Fruit
class Apple : Fruit()

fun main() {
    val appleProducer: Producer<Apple> = object : Producer<Apple> {
        override fun produce() = Apple()
    }
    val fruitProducer: Producer<Fruit> = appleProducer
    val fruit: Fruit = fruitProducer.produce()
    println(fruit)
}
Shows how a Producer of Apple can be assigned to a Producer of Fruit using 'out' variance.
Execution Table
StepActionVariable/TypeValue/ResultNotes
1Define interface Producer with 'out T'Producer<out T>Covariant interfaceAllows T to be returned safely
2Define classes Fruit and AppleFruit, AppleApple inherits FruitApple is subtype of Fruit
3Create appleProducer instanceappleProducer: Producer<Apple>Instance producing AppleOverrides produce() to return Apple
4Assign appleProducer to fruitProducerfruitProducer: Producer<Fruit>fruitProducer = appleProducerAllowed due to 'out' covariance
5Call produce() on fruitProducerfruitProducer.produce()Returns Apple instanceApple is subtype of Fruit, safe to assign
6Assign produced value to fruitfruit: FruitApple instanceFruit variable holds Apple safely
7Print fruitprintln(fruit)Output: Apple@<hashcode>Shows object reference of Apple instance
💡 Program ends after printing the Apple instance as Fruit type
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
appleProducerundefinedProducer<Apple> instanceProducer<Apple> instanceProducer<Apple> instanceProducer<Apple> instance
fruitProducerundefinedundefinedAssigned appleProducer (Producer<Apple>)Producer<Apple> instanceProducer<Apple> instance
fruitundefinedundefinedundefinedApple instanceApple instance
Key Moments - 3 Insights
Why can we assign Producer<Apple> to Producer<Fruit>?
Because the interface uses 'out' modifier, it is covariant. This means Producer<Apple> can be treated as Producer<Fruit> safely since it only produces (returns) values of type T.
Can we pass a Producer<Fruit> to a variable of type Producer<Apple>?
No, covariance only allows assignment from subtype to supertype, not the other way. Producer<Fruit> might produce any Fruit, not necessarily Apple.
Why is 'produce()' allowed to return Apple when the variable type is Producer<Fruit>?
Because Apple is a subtype of Fruit, returning Apple is safe when expecting Fruit. This is the essence of covariance.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is appleProducer assigned to fruitProducer?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Check the 'Action' column for assignment operations in the execution_table.
According to variable_tracker, what is the value of 'fruit' after Step 5?
AProducer<Apple> instance
BApple instance
Cundefined
DProducer<Fruit> instance
💡 Hint
Look at the 'fruit' row and the 'After Step 5' column in variable_tracker.
If we remove 'out' from Producer<T>, what happens when assigning appleProducer to fruitProducer?
ACompilation error due to type mismatch
BAssignment works as before
CRuntime error occurs
DfruitProducer becomes null
💡 Hint
Recall that 'out' enables covariance; without it, subtype assignment is disallowed.
Concept Snapshot
interface Producer<out T> { fun produce(): T }
'out' means covariance: Producer<Apple> can be used as Producer<Fruit>
Allows safe return of subtype as supertype
Covariance works only for return types, not for input parameters
Useful for read-only producers
Full Transcript
This example shows Kotlin's out variance, also called covariance. We define an interface Producer with an out type parameter T. This means Producer is covariant in T. We create classes Fruit and Apple, where Apple inherits Fruit. We make an instance appleProducer of Producer<Apple>. Thanks to covariance, we can assign appleProducer to a variable fruitProducer of type Producer<Fruit>. When we call produce() on fruitProducer, it returns an Apple instance, which is safely assigned to a Fruit variable. This works because Apple is a subtype of Fruit, and covariance allows this safe substitution. Without 'out', this assignment would cause a compile error. Covariance is useful when you only produce (return) values of type T, ensuring type safety.

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