【发布时间】:2020-06-13 19:19:23
【问题描述】:
这是执行短路搜索并将结果映射到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
【问题讨论】:
-
顺便说一句,我不认为
if (<condition>) true else false是一个好主意,因为<condition>单独意味着完全相同! -
是的,确实如此,我认为 IntelliJ 会建议这样做。我只是为了问这个问题而编造的。 (如果您查看我的
exists函数,那正是我所做的。)结果我的想法是使用exists或isNotNull(我稍后重命名)不是一个好主意。即使经过测试,编译器也无法推断出该对象不是null,因此它的使用会出现问题。
标签: kotlin