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!
Legend:
c
- container class for the in and outN, I, L
- hierarchy of classes under testln, li, ll
- list of class N, I, L respectively
```kotlin
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:
- Declaration-Site Variance - Dave Leeds on Kotlin
- Understanding type variance in Kotlin | by André Thiele | ProAndroidDev
- https://freedium.cfd/https://blog.kotlin-academy.com/kotlin-and-variance-navigating-type-relationships-86809d84fd01 - using coffee and vending machines
- https://www.youtube.com/watch?v=6moaoAJui_4