Reputation: 71
I'm looking for a function in Kotlin which stops an iteration once a predicate is fulfilled:
val services = listOf(service1, service2)
...
var res: Result = null
services.stopIfPredicateFulFilled { service ->
res = service.doSomething()
res != null
}
While this example is not really nice since res
is overwritten in each iteration I hope the intention is clear.
forEach
doesn't do the job the way I expect it to be done. So, I was wondering if there isn't anything else.
Upvotes: 1
Views: 423
Reputation: 147911
You can use the functions find { ... }
and firstOrNull { ... }
(they are equivalent, just named differently). They find the first element satisfying the predicate and return that element, ignoring all the remaining elements.
services.find { service ->
res = service.doSomething()
res != null
}
Upvotes: 2