Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get the True Count in Boolean Array in Kotlin

Tags:

java

kotlin

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?

like image 968
Sam Chen Avatar asked Sep 02 '25 16:09

Sam Chen


1 Answers

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.

like image 121
Jon Skeet Avatar answered Sep 04 '25 09:09

Jon Skeet