Jul 10, 2017 · 1 min read
Note: Kotlin also supports use-site variance which is sometimes necessary.
For example, if you write a method which fills a generic MutableList with values, you need to declare the contravariance in the method signature so you don’t need to create a custom class like WritableList:
fun fillWithCats(list: MutableList<in Cat>) {
list.add(Cat("Felix"))
list.add(Cat("Tom"))
}
fun main(args: Array<String>) {
val animals = mutableListOf<Animal>()
fillWithCats(animals)
}