https://kotlinlang.org logo
#getting-started
Title
# getting-started
e

elect

06/13/2022, 7:49 AM
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

ephemient

06/13/2022, 7:52 AM
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

elect

06/13/2022, 7:59 AM
each child has a consequential view on the (root) list, ie the first [0-10], the secon [11-40], etc
m

Michael de Kaste

06/13/2022, 10:16 AM
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

elect

06/13/2022, 10:18 AM
i have the worst I guess, root mutate, child mutate
m

Michael de Kaste

06/13/2022, 10:27 AM
what needs to happen when root adds? Just add it to the final sublist?
e

elect

06/13/2022, 12:04 PM
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

ephemient

06/13/2022, 12:08 PM
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

nkiesel

06/13/2022, 7:01 PM
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?
7 Views