0
0
Kotlinprogramming~30 mins

In variance (contravariance) in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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 in
Create classes Fruit and Apple where Apple inherits from Fruit
Implement the Basket interface in a class called FruitBasket
Use the contravariant Basket type to add an Apple to a basket of Fruit
Print 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
1
Create the Fruit and Apple classes
Create a class called Fruit and a class called Apple that inherits from Fruit.
Kotlin
Need a hint?

Use open class Fruit to allow inheritance, then class Apple : Fruit() to inherit.

2
Create the contravariant Basket interface
Create a generic interface called Basket with a contravariant type parameter T using in. Add a function addItem that takes a parameter of type T.
Kotlin
Need a hint?

Use interface Basket to declare contravariance and define fun addItem(item: T).

3
Implement FruitBasket class
Create a class called FruitBasket that implements Basket<Fruit>. Inside, override addItem to print "Added a fruit to the basket".
Kotlin
Need a hint?

Implement Basket<Fruit> and override addItem to print the message.

4
Use contravariance to add an Apple to FruitBasket
Create a variable basket of type Basket<Apple> and assign it a FruitBasket(). Then call basket.addItem(Apple()). Print the output.
Kotlin
Need a hint?

Assign FruitBasket() to Basket<Apple> variable and call addItem(Apple()).