I've read the kotlin documentation and tried BooleanArray.count(predicate: (Boolean) -> Boolean), but it still returns the size of the array, not the number of true:
val checks = arrayOf(true, false, true, true, true)
val trueCount = checks.count { true }
What's wrong with my code?
You're passing in a predicate that would always return true here:
val trueCount = checks.count { true }
And that would indeed return the size of the array. I'd expect your code to be:
val trueCount = checks.count { it }
In other words, the count of items for which "with the item called it, the expression it returns true".
An alternative you might find easier to read that explicitly checks for equality:
val trueCount = checks.count { it == true }
Personally I tend to avoid comparisons against Boolean literals, but I can see how it's at least arguably clearer in this case.
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