Home > Software engineering >  How can I change an object field in a list and return the list with the changed object?
How can I change an object field in a list and return the list with the changed object?

Time:11-25

I have a data class Post:

data class Post(
    val id: Long,
    val author: String,
    val content: String,
    val published: String,
    var likedByMe: Boolean,
    var likes: Int = 0
)

And here is the list of objects of this class:

val post1 = Post(id = 1, "First", "Content", "0", false, 0)
val post2 = Post(id = 2, "Second", "Interesting", "0", false, 0)
val post3 = Post(id = 3, "Third", "Nothing", "0", false, 0)

val postsList = mutableListOf<Post>(post1, post2, post3)

I need to increment the number of likes for the first post and return the updated list (for example, print it). How can I do this, can you tell me please?

P.S. I think that it can be somehow implemented with a chain of extension-functions, like filter, map, etc., but I don't understand how.

CodePudding user response:

To mutate likes of post1:

postsList[0].likes  = 1

To mutate likes of post1 and return a new list:

val newList = postsList
  .mapIndexed { index, post ->
    if (index == 0)   post.likes
    post                                              // return mutated post1
  }

To clone post1 and then mutate its likes (thereby leaving post1 unchanged), and return a new list:

val newList = postsList
  .mapIndexed { index, post ->
    if (index == 0) post.copy(likes = post.likes   1) // return mutated clone
    else post                                         // return non-mutated posts
  }

Note that each data class has an automatically created copy() function, which creates a clone and can take any of the properties as argument(s) and assigns new values to these properties.

Corrections made according to first comment by @Joffrey.

  • Related