Issue
I need to perform some operations on a mutable list and use its previous value. Something similar to also
except that it should return the previous value.
val localList: List<String> = mainList.alsoButGetPrevious { it.clear() }
Before I write this function, is there an existing one that does this?
Solution
There is no "previous value" in this case. There is only one list and it is modified by clear()
, so even if you would do something like this:
localList = mainList
mainList.clear()
Then localList
would still not contain "previous" value, but it would be empty.
What you need here is to copy the list before clearing it. There is no scoping function for this, because it is specific to lists only. You can implement it by yourself:
val localList = mainList.copyAndApply { clear() }
inline fun <T> MutableList<T>.copyAndApply(block: MutableList<T>.() -> Unit): List<T> {
val result = toList()
block()
return result
}
As noted by @mightyWOZ, toList()
creates a shallow copy of the data, meaning that it contains references to the same object instances as the original list. Above solution works if you need to only clear mainList
or add/remove items from it. However, if you modify objects in mainList
then this change will affect localList
as well. There is no straightforward and universal way to perform a deep copy of the data in Java/Kotlin. If you need this, it is probably better to create utility functions that target your data structures.
Answered By - broot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.