kotlinx.collections.immutable
kotlinx.collections.immutable copied to clipboard
Expose the implementation
The current proposal document is undecided about whether to expose implementation types in the API. I'm confused about that. If only interface types are exposed, how can consumers be sure the collection objects they are dealing with are really immutable? Relying on adherence to the contract seems fragile. A buggy "smart" custom implementation can cause hard-to-diagnose problems far from the source of the error. It defeats the encapsulation benefits of using immutable types in APIs.
Or, expose an abstract superclass that can be implemented only by the standard library.
@btj I'm 100% agree with you. Standard library collections have this problem. But that's fine, List<T>
is not supposed to be immutable, but rather provide a read-only view of a list. So I though maybe some immutable collections exist in kotlin and found this lib. I was so happy installing the new fancy immutables into my project. But what my disappointment was when I found out that whole library is build around interfaces.
The whole thing is about being sure no one can modify the collection from the outside, and then we are given interfaces... 😐
Regarding the solution to the problem. As for me, the approach of C# System.Collections.Immutable seems to be good. Though, they also have interfaces, the implementations are public and final and used all over the place in factory and builder return types.
Related: https://github.com/Kotlin/kotlinx.collections.immutable/issues/106
I do want to be able to write my own implementation for (some) immutable collections and thus I'd like to keep the interface approach, at least a thin abstract classes fwiw.
Someone can write and use implementation for ImmuableCollection
that is not truhly immutable or otherwise buggy but it's not somethink specific to this library. Someone could write buggy implementation for List<T>
as well. We'd have to ban all interfaces.
I'm in favour of having interfaces because then you are not tied to specific immutable implementations in your APIs (e.g. you could have different classes implementing sublists, map keys, etc.).
I have a project where the persistent set interface is useful for a class I'm creating that would then be backed by a persistent set -- specifically, the add, remove, and contains logic is slightly different to a standard set as the elements can be combined or split in those operations. At the moment, I'm using the Kotlin Set interface with custom methods to provide the add/remove/clear persistent operations.
An example similar what I'm doing would be a set of ranges, where adding overlapping ranges would replace those two ranges with a single range over the combined range, etc.. There, you would want a custom PersistentSet implementation to handle that additional complexity.