Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading