Questions
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.
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
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚