Skip to content

Instantly share code, notes, and snippets.

@tomaszpolanski
Created July 3, 2017 16:07
Show Gist options
  • Save tomaszpolanski/b77e4b5c7d877084d46c1d83d4ee92d5 to your computer and use it in GitHub Desktop.
Save tomaszpolanski/b77e4b5c7d877084d46c1d83d4ee92d5 to your computer and use it in GitHub Desktop.
Covariance vs Contravariance
package com.tomek
abstract class Animal(val size: Int)
class Dog(val cuteness: Int): Animal(100)
class Spider(val terrorFactor: Int): Animal(1)
// Covariance
val dogList: List<Dog> = listOf()
val animalList: List<Animal> = dogList // Works!
val spiderList: List<Spider> = animalList // Compiler error, cannot assign List<Animal> to List<Spider>
// Contravariance
interface Compare<in T> {
fun compare(first: T, second: T): Int
}
val dogCompare: Compare<Dog> = object: Compare<Dog> {
override fun compare(first: Dog, second: Dog): Int {
return first.cuteness - second.cuteness
}
}
val animalCompare: Compare<Animal> = dogCompare // Compiler error, cannot assign List<Dog> to List<Animal>
val spider: Compare<Spider> = object: Compare<Animal> { // Works!
override fun compare(first: Animal, second: Animal): Int {
return first.size - second.size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment