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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With