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.

Sign up to request clarification or add additional context in comments.

3 Comments

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: Yup, will add that as an option.
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.
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 }.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.