Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

677
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda