如何找到不为null的第一个元素的方法结果?

Gis*_*zmo 0 kotlin

所以我有解析器,并且想使用第一个确实返回非空值的解析器。我将如何做到最优雅?

return parsers.map { it.parse(content) }.firstOrNull { it != null }
Run Code Online (Sandbox Code Playgroud)

在选择第一个解析器之前会映射所有(百万个)解析器。

return parsers.firstOrNull { it.parse(content) != null }?.parse(content)
Run Code Online (Sandbox Code Playgroud)

parse()再次运行(昂贵?)。

我知道我可以

for (parser in parsers) {
    val result = parser.parse(content)
    if (result != null) {
        return result
    }
}
return null
Run Code Online (Sandbox Code Playgroud)
parsers.forEach { it.parse(content)?.run { return this } }
return null
Run Code Online (Sandbox Code Playgroud)

是我能得到的最短的,但是读起来不好。

我很确定这里有一个快捷方式,我看不到。

mar*_*ran 6

使用序列。它使您的计算变得懒惰,因此您只parse需要根据需要进行多次计算。

return parsers.asSequence()
              .map { it.parse(content) }
              .find { it != null }
Run Code Online (Sandbox Code Playgroud)