I am new to Kotlin and am wrestling with the problem of returning immutable versions of internally mutable lists.
I reviewed the following 'Kotlin: Modifying (immutable) List through cast, is it legitimate?' and understand that immutable lists are really just read-only views which do not expose the modification methods.
I want to have a class which exposes an "immutable" List and still want to take advantage of Kotlins automatic getters (without having to provide all the boilerplate for getting the list or a member of the list)
Is the following a bad idea (or will it cause a problem that may be blocked in future releases)
class Foo {
val names: List<String> = LinkedList;
fun addName(name: String) {
(names as LinkedList).add(name)
}
}
I am looking to allow (for example):
val foo = Foo;
println(foo.names.size)
But still prevent the caller from modifying the internals of the class (at least as much as possible). For example removing elements or clearing the backing list.