Member-only story
Use-Site Variance in Kotlin Explained: When & How It Works
Kotlin is a powerful and flexible programming language that introduces many advanced features to make development easier. One such feature is Use-Site Variance in Kotlin, which helps handle type variance effectively in generic programming. If you’ve ever struggled with understanding variance in Kotlin, this guide will break it down in a simple, easy-to-understand way.
What is Use-Site Variance in Kotlin?
In Kotlin, variance defines how different types relate to each other in a type hierarchy when dealing with generics. Generics allow you to create flexible and reusable code, but without proper variance handling, type safety issues may arise.
Kotlin provides two types of variance:
- Declaration-Site Variance — Defined at the class level using
out
(covariance) andin
(contravariance). - Use-Site Variance — Applied at the point where a generic class is used, rather than where it is declared.
Use-Site Variance is particularly useful when you don’t have control over the generic class declaration but still need to enforce type variance.