Christophe Beyls
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)
}

    Christophe Beyls

    Written by

    Android developer from Belgium, blogging about advanced programming topics.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade