🚀 Enrollments Open for 1:1 Mentorship Scheduled as per your availability 💚Book 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.

1:1 Mentorship

Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.

Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance

Limited slots available each month