Home > Software engineering >  All elements in list getting set to latest item's value
All elements in list getting set to latest item's value

Time:10-07

Needing help with this the below Kotlin code. I am working on a bigger project where I faced this problem and have created a smaller example,

data class EachDay(var day: String, var todo: String)
{

}

data class Week(val list:MutableList<EachDay>)
{

}

fun main() {
    val eachDay = EachDay(day="", todo="")
    var week:Week = Week(arrayListOf<EachDay>())

    eachDay.day="Saturday"
    eachDay.todo="Shopping, Groceries"
    week.list.add(eachDay)
    println("Week"  week)
    eachDay.day="Sunday"
    eachDay.todo="Rest"
    week.list.add(eachDay)
    println("Week"  week)
    eachDay.day="Monday"
    eachDay.todo="Check emails, resume work"
    week.list.add(eachDay)
    println("Week"  week)
}

On running we get:

WeekWeek(list=[EachDay(day=Saturday, todo=Shopping, Groceries)])
WeekWeek(list=[EachDay(day=Sunday, todo=Rest), EachDay(day=Sunday, todo=Rest)])
WeekWeek(list=[EachDay(day=Monday, todo=Check emails, resume work), EachDay(day=Monday, todo=Check emails, resume work), EachDay(day=Monday, todo=Check emails, resume work)])

Have tried variations of above code in many ways just to get the same problem of repeating elements Originally I did not have a data class for list of Items, just declaring it as list of items, so instead of week.list.add it would be week.add, but still with same problem Why are all the elements getting set to same value as element. What am I not understanding here?

CodePudding user response:

You need to either create a new EachDay object or copy it and setting the new values otherwise you will be applying the changes to the same EachDay object.

fun main() {
    var week:Week = Week(arrayListOf<EachDay>())

    week.list.add(EachDay(day="Saturday", todo="Shopping, Groceries"))
    println("Week"  week)
    week.list.add(EachDay(day="Sunday", todo="Rest"))
    println("Week"  week)
    week.list.add(EachDay(day="Monday", todo="Check emails, resume work"))
    println("Week"  week)
}

Or

fun main() {
    val eachDay = EachDay(day="", todo="")
    var week:Week = Week(arrayListOf<EachDay>())

    week.list.add(eachDay.copy(day="Saturday", todo="Shopping, Groceries"))
    println("Week"  week)
    week.list.add(eachDay.copy(day="Sunday", todo="Rest"))
    println("Week"  week)
    week.list.add(eachDay.copy(day="Monday", todo="Check emails, resume work"))
    println("Week"  week)
}

I would go with the first one.

  • Related