这是执行短路搜索并将结果映射到Boolean的惯用方式吗?

val foos = mutableListOf<Foo>()
...
fun fooBar(bar: Bar) = if (null != foos.find { it.bar == bar }) true else false

基本上,我一直在寻找与
fun Any?.exists() = null != this
fun fooBar(bar: Bar) = foos.find { it.bar == bar }.exists()

对于可能返回null的任何内容,这似乎都是有用的模式。

编辑:

我决定编写类似于filterIsInstance()的简单扩展功能:
inline fun <reified R> Iterable<*>.findIsInstance(): R? {
    for (element in this) if (element is R) return element
    return null
}

用法示例:
val str = list.findIsInstance<String>() ?: return

最佳答案

我相信您正在寻找 any ,如果任何元素匹配给定谓词,则返回true,并且正在短路

fun fooBar(bar: Bar) = foos.any { it.bar == bar }

关于kotlin - 映射单个对象的惯用方式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62364570/

10-11 22:35
查看更多