Trying to make my own persistent mutableset

I feel like I’m really close. Likely an easy question and I’m not searching on the right terms: I’d like to have a fake MutableSet where I do strange stuff with the backing store to save it whenever it is edited.

which I think means a Delegate.
val myFunnySet:MutableSet<String> by MyLessFunnyMutableSet()

And I got as far as class MyLessFunnyMutableSet : AbstractMutableSet<String>() {... which required me to override fun add(element: String): Boolean { and iterator() and size(). This all makes sense!

…Until I get to what the override fun iterator(): MutableIterator<String> = myFunkyStorage.get().toMutableSet().iterator() returns: a MutableIterator.

hold up. If someone mutates that iterator with a remove() - that feels like it will only act on the one-off MutableSet I just created. I didn’t want to create a new stand-alone set, I want to “catch” all the adds/removes back to myself!

Which makes me wonder if I’m doing it wrong. “here is a class property. It is a val, no reassigning it. It is a mutableset, feel free to add or remove elements, or even addAll, because the backing store will be notified of every modification. And no matter what, myFunkyStorage will be told about the mutation”

Do I have to implement the MutableSet interface from scratch?

1 Like

Simply, you need to define your own MyLessFunnyMutableSetIterator that extends MutableIterator and basically does all your funky storage actions if that makes sense.