Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
44: Variance: in and out
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:
- Modify the
Handlerinterface to use the correct variance keyword (inorout) so that it can be used as a consumer. - Implement a
LogAllHandlerthat implementsHandler<Any>. - In the
mainfunction, pass theLogAllHandlerinto thedispatchMessagefunction, which specifically requires aHandler<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
}There are no comments for now.