Home > Net >  kotlin, what is better way to aggregate the result from a list of functions
kotlin, what is better way to aggregate the result from a list of functions

Time:10-11

In kotlin. Having a list of functions, every one returns true or false. If one of the function returns true, then the final return should be true. Other wise return false.

What is the better way to write the kotlin function for it?

Having one function but feel it could be written better, any suggestion?

fun returnTheResultFromTheListOfFunctions(funcList: MutableList<FunctionType)
   return if (funcList.isEmpty()) {
            true
        } else {
            for (func in funcList) {
                if (func.getResult())
                    return true
            }
            false
        }
}

CodePudding user response:

You want true if the list is empty or func.getResult() is true for any element, so you can pretty directly convert the semantics to code:

return funcList.isEmpty() || funcList.any { it.getResult() }
  • Related