I have a two-level hierarchy with a root and one o...
# getting-started
e
I have a two-level hierarchy with a root and one or more children. Each of these children have a list of elements they need to track, and I'd like also to have somehow a "root" list in the root that incorporates all the children lists. Is there a (easy/stdlib) way to have just the root list and then each child simply manages a subset/view of this list (removing/adding)? Ps: no synch problems, everything is serial
something in the direction of `subList`(here) but I guess if the root or the first child modifies the list, then I have to update indices for all the other children..
e
if the children are immutable, sure. if they are mutable you will have to define your requirements more specifically
Copy code
val child = object : AbstractCollection() {
    override val size get() = root.count { isChild }
    override fun iterator() = root.filter { isChild }.iterator()
}
e
each child has a consequential view on the (root) list, ie the first [0-10], the secon [11-40], etc
m
I had the same issue when I had some sealed class which was viewed by the root and the implementations managed by its children. depending on your usage combination: • root view, child view • root view, child mutate • root mutate, child mutate • root mutate, child view there are different solutions. if you have root view and child mutate, you can simply have root be a value that on every request returns a new list based on the children. You can make it better by defining your own concatenation iterator
e
i have the worst I guess, root mutate, child mutate
m
what needs to happen when root adds? Just add it to the final sublist?
e
yep
atm I'm leaning toward a
map<name, ArrayList>
on the root containing the corresponding children lists and then forwarding the methods I need
e
if the root exposes a MutableList, you'll have to figure out what to do with insertions and removals at any index and before or after any listiterator
if it's a MutableCollection, then you "only" have to figure out what to with removals before any mutableiterator and additions to the whole collection
n
do I understand correctly that each child is defined as an index range of the root list? Thus, a list of items and a list (or map if children are not identified by index) of IntRange would do the trick?