Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply logical AND to a list of boolean values

Tags:

kotlin

fold

Consider a mutable list with boolean values,

MutableList{true, false, false}

How to return the boolean value after performing a logical AND on all of the values within the list using Kotlin fold?

like image 539
musica Avatar asked Sep 05 '25 03:09

musica


1 Answers

This is a common case for fold operator, you mentioned.

val list = mutableListOf(true, false, false)

val result = list.fold(initial = true) { accumulator, nextItem ->
    accumulator && nextItem
}

alternatively you can just check if list contains even one false using:

val result = (false !in list)
like image 172
Sebastian Pakieła Avatar answered Sep 08 '25 18:09

Sebastian Pakieła