Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin- Is there any way to update a single field in collection item in Kotlin without foreach?

Tags:

foreach

kotlin

I am working on Android application using kotlin. I am pretty much new to kotlin and I have the following scenario.

I have the list of users in a List collection object with the fields such as firstName , lastName, mobile and hasDeleted

var myList: List<Users>
myList = <I have list of users here>

I would like to update only one flag hasDeleted with the value true for each Users.

I understand that we can use foreach to update the value. But, I would like to know if any other approach I can follow.

like image 957
Rakesh L Avatar asked Nov 14 '25 18:11

Rakesh L


1 Answers

The only reason for not using forEach is if your Users object is immutable (which you should at least consider) and it is a data class defined as follows:

data class Users(val firstName: String, 
                 val lastName: String, 
                 val mobile: String, 
                 val hasDeleted: Boolean)

If this is what you have, then map is your best option, since you can no longer change a Users object with hasDeleted = true because they are not mutable. In this case, you should use the following which will return a list with the updated Users objects.

myList.map { it.copy(hasDeleted = true) }

Other than this specific case, I see no good reason to avoid using forEach.

like image 93
João Dias Avatar answered Nov 17 '25 09:11

João Dias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!