🚀 Enrollments Open for Jetpack Compose Cohort 2 — 7 Days of Live Learning to Build Modern Android UIs 💚Join Now
KotlinIntermediate4 min
Covariance in Kotlin?

Answer

Covariance allows you to use a subtype in place of a supertype. In Kotlin generics, it is denoted by the `out` keyword.

Producer (out)

  • If a generic class only returns (produces) type T, it can be covariant.
  • `List<out T>` is covariant. A `List<String>` IS A `List<Any>`.

```kotlin val strings: List<String> = listOf("A", "B") val objects: List<Any> = strings // Valid because List is covariant (out T) ```

Contravariance (in)

  • If a generic class only consumes type T, it is contravariant.
  • Denoted by `in`.
  • `Comparable<in T>`. A `Comparable<Any>` can compare Strings.

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

Accelerate Your Growth

Don't just learn concepts in isolation. Build production-ready Android apps with expert guidance.

Live Interactive Sessions
Code Reviews & Feedback
Real-world Projects
Career Guidance

Limited seats available for next cohort