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.
count { it }
instead of count { true }
The argument to count
isn't a value to look for in the array; it's a predicate: a function that takes one argument and returns true
or false
. The predicate is called once for each item in the array, and the value ( true
or false
) returned by that predicate determines whether the item is counted or not. So the result is the number of items in the array for which the predicate evaluated to true
.
In this context, writing { true }
is shorthand for { value -> true }
, and is a constant function. It will always return true
, regardless of what the value
is. So "count the number of items for which { true }
returns true
" is exactly the same as "count the number of items" .
What you want instead is to count the number of items where the value is true
. The predicate you should use is { value -> value }
, which is a function that takes a single argument and returns the value of that argument. Since a single lambda parameter is implicitly named it
when you don't give it a name, the shorthand for { value -> value }
is just { it }
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.