I was reading about reasons why kotlin does not have wildcards (https://kotlinlang.org/docs/reference/generics.html). It all came to the declaration-site variance. We have <in T>
and <out T>
constructions which should replace wildcards. I think I understood how <out T>
works but I have troubles with <in T>
.
So in java we could write something like this:
public List<? extends Number> list1;
public List<? super String> list2;
First case after initialization becomes read only list (though not perfectly immutable cause we could clear it) which could be read if we treat every element as Number.
Second case is write only (though we could read it if we treat every element as Object). We could write there String and it subclasses.
In Kotlin I was able to recreate list1 example using <out T>
like this:
class Service {
val container = Container(mutableListOf("1", "2", "3"))
}
class Container<T>(var list1: MutableList<out T>)
Finally I tried something similar with <in T>
thinking that I could recreate list2 example, but I failed:
Can someone explain to me how to achieve my list2 example in Kotlin? How should I use <in T>
construction in proper way?