Michael Friend
02/05/2020, 4:48 PMprivate 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 seconddiesieben07
02/06/2020, 7:17 AMlistOfStrings
field.
The second example creates one (private) field and a getter.diesieben07
02/06/2020, 7:33 AMMichael Friend
02/06/2020, 7:23 PMMichael Friend
02/06/2020, 7:24 PMprivate var _stringsVar = "test"
val stringsVal = _stringsVar
then reassigning _stringsVar
wouldn’t affect the value of stringsVal
?diesieben07
02/06/2020, 7:25 PMbdawg.io
02/10/2020, 12:54 AMList<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).
val listOfStrings = object : List<String> by _listOfStrings {}