y
11/15/2022, 2:12 PMprivate set
to do this, but it seems like I can still mutate the value from outside the class.Stephan Schroeder
11/15/2022, 2:14 PMprivate set
should indeed do this. can you provide the code?
I hope you mean outer mutability (/reassignability) x.list = otherList
, not inner mutability x.list.clear()
Making the setter private will block the first one, but not the second one (since it only invokes the getter)y
11/15/2022, 2:20 PMclass Foo() {
private var bar: Bar = Bar()
class Bar() {
var items: MutableList<Int> = mutableListOf()
private set
}
fun doTheThing() {
bar.items.clear() //compiles and works
}
}
y
11/15/2022, 2:21 PMprivate set
is just for the binding, the value itself is still mutableNuru Nabiyev
11/15/2022, 2:23 PMSam
11/15/2022, 2:23 PMStephan Schroeder
11/15/2022, 2:23 PMprivate set
makes the setter private, but bar.items.clear()
doesn't invoke the setter.y
11/15/2022, 2:24 PMStephan Schroeder
11/15/2022, 2:25 PMLandry Norris
11/15/2022, 2:25 PMy
11/15/2022, 2:25 PMLandry Norris
11/15/2022, 2:26 PMStephan Schroeder
11/15/2022, 2:28 PMclass Bar() {
private var _items: MutableList<Int> = mutableListOf()
val items: List<Int> get() = _items // is typesafe but could run into ConcurrentModificationExcaption in multithreaded code, if the read-only copy is iterated on while the mutable version is changed
}
or harden this approach (the former approach still allows casting the reference back to MutableList
) like this
class Bar() {
private var _items: MutableList<Int> = mutableListOf()
val items: List<Int> get() = _items.toImmuatableList() //return only a static snapshot
}
with toImmuatableList
coming from this lib https://github.com/Kotlin/kotlinx.collections.immutabley
11/15/2022, 2:33 PMy
11/15/2022, 2:34 PMy
11/15/2022, 2:34 PMStephan Schroeder
11/15/2022, 2:34 PMLandry Norris
11/15/2022, 2:35 PMinterface Bar {
val items: List<Int
}
class Foo: Bar {
override val items: MutableList<Int> = mutableListOf(0)
}
Any usage of Bar#items will be immutable.Stephan Schroeder
11/15/2022, 2:35 PMvar
but val
I updated the code.y
11/15/2022, 2:37 PM