Home > Blockchain >  How to increase or decrease value of an object parameter in an array in Kotlin
How to increase or decrease value of an object parameter in an array in Kotlin

Time:03-25

I am trying to adjust (increase and decrease) the value of an object parameter contained in an array. The code structure is basically something like this:

data Class MyData (val id:String, var count:Int)

 private val listItems = MutableLiveData<ArrayList<MyData>>()

fun increaseItemCount(id:String) {
     listItems.value?.find { item ->
         item.id == id }?.count?.plus(1) }

I tried using the increaseItemCount function above but couldn't get it to work. Any idea on how I can implement this?

CodePudding user response:

The problem is basically that you increment the value of count - and then throw it away. Int.plus(...) is nothing else than between integers. So, you are calculating count 1 but you are not using the result.

If you intend to increment the value of count and store that value in the variable count, you can alter your function in the following way:

fun increaseItemCount(id:String) {
    listItems.value?.find { item ->
        item.id == id }?.let { it.count  = 1 } }
  • Related