【问题标题】:Idiomatic way to map single object映射单个对象的惯用方式
【发布时间】: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 (&lt;condition&gt;) true else false 是一个好主意,因为&lt;condition&gt; 单独意味着完全相同!
  • 是的,确实如此,我认为 IntelliJ 会建议这样做。我只是为了问这个问题而编造的。 (如果您查看我的 exists 函数,那正是我所做的。)结果我的想法是使用 existsisNotNull(我稍后重命名)不是一个好主意。即使经过测试,编译器也无法推断出该对象不是null,因此它的使用会出现问题。

标签: kotlin


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    相关资源
    最近更新 更多