Home > database >  How to check if boolean property of an object in array is true with Kotlin?
How to check if boolean property of an object in array is true with Kotlin?

Time:08-08

I am trying to validate an array in Android app written with Kotlin. It is an array of objects. This is the code that always returns 0. This might be even some deeper problem, but for now i am looking for any other way to get the count right.

private fun count(array: Array<Item>): Int {
    val selectedItemCount = 0
    array.forEach { item ->
        if (item.isSelected) selectedItemCount   1
    }
    return selectedItemCount
}

Basically my problem is that if the count is 0 and none items are selected i want to display no items selected message, otherwise navigate to next screen. I believe that i got this part right. When i log the count every time it returns 0 although the items selected are true within array.

Any help please?

CodePudding user response:

You can improve the code by just using the count with predicate function to do the same in a cleaner way (in this example, the function counts all elements having isSelected set to true):

private fun count(array: Array<Item>): Int {
    return array.count { it.isSelected }
}

There are a few problems in the original question:

  • in the first line, you create val (which is final type, so you can't change it's value). You can use var instead
  • this operation: selectedItemCount 1 adds 1 to selectedItemCount and returns it's value (it's not modifying the input variable). You can use selectedItemCount = 1 operator instead (add and update the variable), or simply selectedItemCount if you just want to increment by one

CodePudding user response:

Try this instead

array.forEach { item ->
        if (item.isSelected) selectedItemCount  = 1
    }
  • Related