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

673
Vistas
Kotlin - Companion Object changes it value when the variable is changed

I am having a data class which is having data in form of Lists (Companion Objects). I assign these lists to my variables (lists) in Activity class according to my requirement. The problem is that when I change some list (that was assigned the companion object list value) in Activity class then Companion object list is also changed. Why is this happening? Are Companion objects as assigned by reference? How to avoid this? I want if the variable list of Activity class is changed then companion object list should retain its value.

My code Data List

class DataLists {
    companion object {
        val CountryList: List<CountryDataStructure> = listOf(
            CountryDataStructure(1, "USA"),
            CountryDataStructure(2, "Canada"))
    }
}

Activity Class

var CountryData = DataLists.CountryList
CountryData[0].Name = "United States of America" 
//Here the Companion object list (CountryList) i.e. DataList is also changed and have 
//values "United States of America" and "Canada" while I expect this to have "USA" and "Canada"
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Everything besides inline classes and primitives is always passed by a reference copy, not a deep value copy. Inline classes and primitives are sometimes passed by value copy, but the distinction hardly matters since they're immutable.

Since your CountryDataStructure class is mutable, you need to manually copy both the list and the items in the list, which can be done using the map iterator function and the data class copy() function:

val countryData = DataLists.CountryList.map { it.copy() }
countryData[0].Name = "United States of America" 
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