Variance in Kotlin

Paste the following example in intellij and uncomment each line, reading the errors and which specific fields produce those errors.

Maybe this will help you understand Variance a bit better. It helped me!


  • c - container class for the in and out
  • N, I, L - hierarchy of classes under test
  • ln, li, ll - list of class N, I, L respectively

open class N
open class I : N()
open class L : I()

data class c<in InType : I, out OutType : I>(
    private val _in: List<InType>, // try to remove keyword private here
    val _out: List<OutType>

fun main() {
    val ln: List<N> = listOf(N())
    val li: List<I> = listOf(I())
    val ll: List<L> = listOf(L())

    // test in
    val cii: c<I, I> = c(li, li)
    val cll: c<I, I> = c(ll, ll)
//    val cin = c(li, ln) // nop for ln. only I or children expected
//    val cni = c(ln, li) // nop for ln. only I or children expected

    // test out
    val oln: List<N> = cll._out
//    val oll:List<L> = cll._out // nop. only I or N (parents) expected

Other links which I found useful on this topic: