4

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?

2 Answers 2

16

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.

3
  • 2
    It might help to consider checks.count { it == true }: that clearly counts what you want, but has the same effect as the more concise checks.count { it }.
    – gidds
    Sep 5, 2020 at 16:13
  • @gidds: Yup, will add that as an option.
    – Jon Skeet
    Sep 5, 2020 at 17:04
  • Ta. Though I wasn't suggesting people use that — merely that it might help to explain the shorter version if its operation wasn't obvious.
    – gidds
    Sep 5, 2020 at 18:22
8

Use 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 }.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.