Kotlin Generics: Understanding in, out, and where Keywords

Android-World
2 min readMay 2, 2023
Photo by Louis Tsai on Unsplash

In Kotlin, the generics system provides powerful features to ensure type safety while allowing flexibility. This blog post will explore the <in, out, where> keywords in Kotlin generics with examples ranging from basic to advanced.

The out Keyword: Covariance

The out keyword is used to mark a type parameter as covariant. It means that the type parameter can only be produced (returned) by the class or function, and not consumed (passed as an argument). Here's a simple example:

abstract class Producer<out T> {
abstract fun produce(): T
}

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

fun main() {
val producer: Producer<Any> = StringProducer()
println(producer.produce())
}

In this example, the Producer class has a covariant type parameter T. As a result, we can use a StringProducer instance where a Producer<Any> is expected.

The in Keyword: Contravariance

The in keyword is used to mark a type parameter as contravariant. It means that the type parameter can only be consumed (passed as an argument) by the class or function, and not produced (returned). Here's an example:

interface Consumer<in T> {…

--

--

Android-World

Experienced Senior Android Developer with a passion for developing high-quality, user-friendly apps. https://twitter.com/MyAndroid_World