Such as those readily available in Java,e.g. List.copyOf(collection)
, or similar native implementation. In particular, I would expect, that toList()
, calling on a collection or a sequence, would return an immutable snapshot of that collection or sequence, and calling toList()
again would return the same instance.
A related side question - what is the idiomatic solution to frequent situation, when you get List
in a constructor, and you want to store (a copy) of this (seemingly unmodifiable) list?
In Java, I would go with something like this:
class Service {
private List<String> list;
public Service(List<String> list) {
this.list = List.copyOf(list);
}
}
In Kotlin, I can do either:
class Service(val list: List<String>) {
...
}
or
class Service(list: List<String>) {
val list = list.toList()
...
}
The problem is, that the first solution is unsafe (must make an assumption that the caller would not modify the list), while the second solution is inefficient (every such call copies elements around and creates another snapshot of the collection).
Which solution would you use? I would consider the first solution as idiomatic, and would use in my code where I can make that assumption.
However, if I would like to create some independent library, that makes no assumption about outer environment, I would need to resort to the second solution, wouldn’t I?
Or is there something better? Isn’t this a design flaw of the Kotlin collection framework?