Mohammad Jahidul Islam
01/18/2023, 5:50 AMclass VeganFood: Food()
interface Seller<out T>
class FoodSeller: Seller<Food>
class VeganFoodSeller: Seller<VeganFood>
interface Consumer<in T>
class Person: Consumer<Food>
class Vegan: Consumer<VeganFood>
fun main() {
var foodSeller: Seller<Food>
foodSeller = FoodSeller()
foodSeller = VeganFoodSeller()
var veganFoodConsumer: Consumer<VeganFood>
veganFoodConsumer = Vegan()
veganFoodConsumer = Person()
}
Does anyone explain covariant and contravariant in Kotlin, please recommend any discussion on this topicKristian Nedrevold
01/18/2023, 8:22 AMKristian Nedrevold
01/18/2023, 8:22 AMMichael de Kaste
01/18/2023, 1:13 PM<in T>
means the T can only go IN the class e.g.: fun add(thing: T): Boolean
<out T>
means the T can only go OUT the class e.g.: fun get(index: Int): T
most things are both in and out, and thus just T
but a consumer, like the name suggest, would probably only need to have things go IN it. same goes for a producer, but for OUT.
is that clear enough?mkrussel
01/18/2023, 1:26 PM