When keep a private property of a mutable data hol...
# codingconventions
m
When keep a private property of a mutable data holder but exposing an immutable, is there a functional difference between
Copy code
private val _listOfStrings = mutableListOf<String>()
val listOfStrings : List<String> = _listOfStrings
// and 
private val _listOfStrings = mutableListOf<String>()
val listOfStrings : List<String> 
    get() = _listOfStrings
Which one is better convention? I like how the first one is more concise but examples often show the second
d
The first example creates two (private) fields in the class, both pointing to the same object. It then generates a getter for the
listOfStrings
field. The second example creates one (private) field and a getter.
👍 1
So as far as convention goes I would go with the 2nd example, because it correctly reflects your intent.
👍 1
m
Ahhh that makes sense. 2 creates a property with no backing field, while 1 creates a second field pointing to the same reference. Thanks!
So does that mean that if you had
Copy code
private var _stringsVar = "test"
val stringsVal = _stringsVar
then reassigning
_stringsVar
wouldn’t affect the value of
stringsVal
?
d
Correct
👍 1
b
Just because you return
List<String>
doesn't make it immutable. Anyone can just perform
listOfStrings is MutableList<String>
to smart cast it as mutable. You would need to protect it if you truly need read-only guarantees (unless they do reflection to bypass it).
Copy code
val listOfStrings = object : List<String> by _listOfStrings {}