Skip to Content
Course content

44: Variance: in and out

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember a developer I worked with a few years ago—let's call him Mark. Mark was building a plugin system for a data processing engine. He had a List<String> of configuration keys, and he tried to pass that list into a function that simply printed a List<Any>. He was genuinely frustrated when the compiler yelled at him. "But a String IS an Any!" he argued. He was right, logically, but he had hit the wall of invariance. He didn't realize that by default, generic types in Kotlin are invariant, meaning List<String> is not a subtype of List<Any>, even though String is a subtype of Any.

Variance is essentially the way we tell the compiler how the subtyping relationship of a generic class relates to the subtyping relationship of its type parameters. It sounds academic, but it boils down to one simple question: are you producing values, consuming them, or both?

The 'out' Keyword for Producers

When a class only ever returns a type T and never takes it as an input, we call that class a producer. In this case, we can use the out keyword to make the type covariant. Covariance means that if String is a subtype of Any, then Producer<String> is also a subtype of Producer<Any>.

interface Source<out T> {
    fun next(): T
}

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

fun main() {
    val stringSource: Source<String> = object : Source<String> {
        override fun next() = "Hello Variance!"
    }
    
    // This works because Source is covariant (out T)
    printAnything(stringSource)
}

Why does this work? Because the compiler knows that Source<out T> will only ever give you a T. If it's a Source<String>, every single thing coming out of it is a String, and since every String is an Any, it's perfectly safe to treat it as a Source<Any>. If we allowed T to be used as an input (like a set(value: T) method), the compiler would stop us. Why? Because if you treated a Source<String> as a Source<Any>, you might try to put an Int into it, which would crash the program at runtime. out protects you from that.

The 'in' Keyword for Consumers

Now, let's look at the opposite. What if your class only consumes T? This is a consumer, and we use the in keyword to make it contravariant. Contravariance flips the relationship: if String is a subtype of Any, then Consumer<Any> is actually a subtype of Consumer<String>.

I'll admit, this is usually where people's brains start to itch. It feels backwards. But think about it this way: if I have a tool that can process any object (Consumer<Any>), that tool is more than capable of processing a String. Therefore, I can use a Consumer<Any> anywhere a Consumer<String> is expected.

interface ComparableWith<in T> {
    fun compare(item: T)
}

fun checkString(comparer: ComparableWith<String>, value: String) {
    comparer.compare(value)
}

fun main() {
    val anyComparer = object : ComparableWith<Any> {
        override fun compare(item: Any) {
            println("Comparing $item")
        }
    }
    
    // This works because ComparableWith is contravariant (in T)
    checkString(anyComparer, "Kotlin")
}

In this example, anyComparer is a generalist. Since it can handle any object, it's a perfectly valid substitute for a specialist that only handles strings. Note that you cannot use T as a return type in a contravariant interface; the compiler will block you to ensure type safety.




📋 Practical Task

Refactoring the Event Handler for Type Variance

You are working on a notification system. Currently, you have a Handler interface and a Dispatcher class. However, the code is too rigid. You cannot use a general Handler<Any> (which logs all events) to handle specific Handler<String> events, even though it should be logically possible.

Your Task:

  1. Modify the Handler interface to use the correct variance keyword (in or out) so that it can be used as a consumer.
  2. Implement a LogAllHandler that implements Handler<Any>.
  3. In the main function, pass the LogAllHandler into the dispatchMessage function, which specifically requires a Handler<String>.
interface Handler<T> {
    fun handle(event: T)
}

fun dispatchMessage(handler: Handler<String>, message: String) {
    handler.handle(message)
}

fun main() {
    // TODO: Implement LogAllHandler here
    // TODO: Call dispatchMessage using the LogAllHandler
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.