Discover how a simple keyword can save your program from confusing type errors!
Why Out variance (covariance) in Kotlin? - Purpose & Use Cases
Imagine you have a box that can hold fruits. You want to pass this box around different parts of your program, but sometimes you only want to read fruits from it, not put new ones in. Without a clear rule, you might accidentally put the wrong fruit inside, causing confusion.
Manually checking and converting types every time you pass around the box is slow and error-prone. You might write extra code to ensure safety, but it becomes messy and hard to maintain. Mistakes can cause crashes or bugs that are hard to find.
Out variance (covariance) lets you say: "This box only gives out fruits, it won't accept new ones." This rule helps the compiler understand your intent, so it safely allows you to use the box in many places without extra checks or errors.
fun printFruits(box: Box<Fruit>) { val fruit = box.get() /* but what if box is Box<Apple>? */ }fun printFruits(box: Box<out Fruit>) { val fruit = box.get() /* safe to read any Fruit subtype */ }It enables safe and flexible code that can work with different types of data without risking type errors.
Think of a streaming service that provides movies. Using out variance, the service can guarantee it only delivers movies (or subtypes like documentaries) without allowing users to add new content directly, keeping things safe and clear.
Out variance helps you safely read data from generic types.
It prevents accidental writes that could cause errors.
It makes your code more flexible and easier to maintain.