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

Time:09-22

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.

CodePudding user response:

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.

CodePudding user response:

You can simply use map for it:

myList.map { it.hasDeleted = true }

it will update all hasDeleted as true in the list.

CodePudding user response:

Yes you can do it with the following approach

var myList: List<User>
myList.map { it.hasDeleted = true}

The map will replace the value of hasDeleted for all the list items to true/false, whatever you will provide.

Here is a tested sample with expected results.

enter image description here

  • Related