In variance (contravariance) in Kotlin
📖 Scenario: Imagine you are building a simple system to handle different types of fruits and their baskets. You want to learn how Kotlin's in keyword helps with contravariance, allowing you to safely use a basket that can accept fruits or their supertypes.
🎯 Goal: You will create a generic interface with contravariance using in, then implement it and use it to add fruits to baskets safely.
📋 What You'll Learn
Create a generic interface called
Basket with contravariance using inCreate classes
Fruit and Apple where Apple inherits from FruitImplement the
Basket interface in a class called FruitBasketUse the contravariant
Basket type to add an Apple to a basket of FruitPrint confirmation messages showing the fruit added
💡 Why This Matters
🌍 Real World
Contravariance is useful when you want to write flexible code that can accept inputs of a more general type, such as event handlers or consumers in UI programming.
💼 Career
Understanding variance helps you work with Kotlin generics safely and effectively, a skill important for Android development and backend Kotlin projects.
Progress0 / 4 steps