Can someone give an example showing how a persistent collection is different from an immutable collection in kotlinx.collections.immutable?
I've found this explanation, however I don't fully understand it without an example:
A Persistent collection is one that can only be modified by making updates to the underlying data structures pointers which now link the unaffected parts of the collection with new updated parts. On the other hand, an Immutable collection is one that cannot be changed under any circumstance. Once the collection exists, its contents are fixed.
In terms used in the kotlinx.collections.immutable
library, an immutable collection is a collection that is read-only and provides an additional contract that its contents can not be modified after the collection is created. Read-only collection interfaces do not have this contract and only guarantee that the collection can not be modified through the interface, while an actual implementation of a read-only collection can be mutable.
Collection (read-only)
/ \
ImmutableCollection MutableCollection
Immutable collections do not provide additional APIs compared to the corresponding read-only collections, except that the subList()
method of ImmutableList
is overridden to return an ImmutableList
as well, and keys
, values
, and entries
properties of ImmutableMap
are also overridden to return immutable collections.
A persistent collection is a subtype of immutable collection that provides modification operations — the operations that return a new instance of a persistent collection with modified content:
val original = persistentListOf("a", "b")
val modified = original.add("c")
// original still contains [a, b]
// modified contains [a, b, c]
Persistent collection modification operations are usually implemented in a way that avoids copying the entire content of the original collection and shares the unchanged parts of the internal data structure with the original collection. Such implementation requires knowing about details of the collection internal data structure and thus must be a member function of the collection interface having access to its internal implementation details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With