Kotlin:当谓词满足时停止迭代的函数

问题描述 投票:1回答:1

我正在Kotlin中寻找一个函数,它在谓词完成后停止迭代:

val services = listOf(service1, service2)
...
var res: Result = null
services.stopIfPredicateFulFilled { service ->
    res = service.doSomething()
    res != null
}

虽然这个例子并不是很好,因为res在每次迭代中被覆盖,但我希望这个意图是明确的。 forEach没有像我期望的那样完成工作。所以,我想知道是否没有别的东西。

kotlin built-in
1个回答
2
投票

你可以使用函数find { ... }firstOrNull { ... }(它们是等价的,只是命名不同)。他们找到满足谓词的第一个元素并返回该元素,忽略所有剩余元素。

services.find { service ->
    res = service.doSomething()
    res != null
}
© www.soinside.com 2019 - 2024. All rights reserved.