Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

675
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!