i have a mutable list of objects, and a reference ...
# announcements
l
i have a mutable list of objects, and a reference to one of the objects in that list. i want to keep every object from start until (including) the object i have a reference to, and drop everything that comes afterwards. I see countless ways to do this (e.g.
myList.dropLast(myList.size - 1 - myList.indexOf(thatObject))
) but none that really satisfies me in terms of readability. can you guys give me some suggestions? I figured the best way would involve
myList.retainAll()
somehow but i couldnt find a good way to make use of it
w
Check if this is what you are looking for?
l
ah, sorry, its actually an
ObservableList
from TornadoFX which doesn't have a
.takeUntilItem()
function unfortunately. I thought it had the same functions as a normal
MutableList
but apparently not
but otherwise yes,
myList.retainAll(myList.takeUntilItem(thatItem))
would have been what I'm looking for, though I'm still not sure whether thats the best approach as it seems inefficient
oh i also just realized that my original example is incorrect as it returns a new list rather than modifying
myList
w
takeUntilItem
was my extension
list.take(min(list.indexOf(item) + 1, list.size))
l
oops, im stupid your extension function returns a new list, but i want it to modify the list instead. i found the solution now,
ObservableList
has a function
.remove(from: Int, to: Int): Unit
which is exactly what i need. still, thanks for your help
👍 1
w
no problem, also let me provide an advice, try lay down the cases, as I did with the solution above, in a test file. For me it makes more easy to find a solution, and more confident about it - and about to refactor it. Also helps in identifying corner cases, as the last item, no item, etc. 🙂