xetra11
xetra11

Reputation: 8835

Kotlin: Public getter returns immutable list but private getter should return mutable list

I want my class to have a field that is return an immutable list for all public accesses but inside the object instance I want the list to be mutable so I can add elements to it.

   class GrammarParser {
    private val grammars: List<Grammar> = mutableListOf()
    get() = field.toList()
   }

Try

 class GrammarParser {
    private val _grammars: MutableList<Grammar> = mutableListOf()
    val grammars: List<Grammar>
    get() = this._grammars.toList()
   }

I tried this but am unsure if this is considered good practice?

Upvotes: 2

Views: 1387

Answers (1)

Utku &#214;zdemir
Utku &#214;zdemir

Reputation: 7725

In Kotlin, every MutableList<T> is also a List<T>. So, you can create a MutableList in a private field, and declare an additional field of type List that points to the same object. Inside the class, you can use the mutable reference to modify the list, and expose the List to outside.

Example:

class GrammarParser {
    private val mutableGrammars = mutableListOf<Grammar>()
    val grammars: List<Grammar> = mutableGrammars
}

In your second example, you create a copy (snapshot) of the list every time you call the getter. This means, after you call the getter and got a list, even if the _grammars is modified somewhere else, the changes will not be reflected in the read-only list view you got the reference of. This might be something you want - then what you are doing is ok. But if that's not something you are looking for, then the example I gave above will avoid the copying.

Upvotes: 7

Related Questions