- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
鉴于以下从 Kotlin Koans 中提取的代码:
fun Shop.findAnyCustomerFrom(city: City): Customer? {
// Return a customer who lives in the given city, or null if there is none
return customers.firstOrNull { it.isFrom(city) }
}
我自己的解决方案使用了 customers.find
。两者都适用于 koan 场景。
firstOrNull
的文档和 find
看起来很相似。
这两个函数有什么区别?
最佳答案
在 2014 年的这个帖子中,Kotlin 社区成员和 JetBrains 工作人员讨论了不同方法的优点 find
和 firstOrNull
:
https://youtrack.jetbrains.com/issue/KT-5185
虽然不是官方声明,但 JetBrains 的员工 Ilya Ryzhenkov 将其描述为:
I think we can undeprecate
find
and make it an alias tofirstOrNull
. Much likeindexOf
has well-known semantics,find
is also widely recognised as "find first item matching predicate or return null if nothing is found". People who like precise meaning can usefirstOrNull
,singleOrNull
to express the intent.
换句话说:
find(predicate)
和 firstOrNull(predicate)
行为和 find
相同可以认为是 firstOrNull
的别名find
保留为别名,因为对于尚未熟悉这些 Linq 风格(或 功能)方法的程序员来说,它更直观且易于发现。实际上 Array<out T>.find
的定义没有定义为别名,而是作为包装器(尽管优化编译器会将其内联,从而有效地使其成为别名):
https://github.com/JetBrains/kotlin/blob/1.1.3/libraries/stdlib/src/generated/_Arrays.kt#L657
@kotlin.internal.InlineOnly
public inline fun <T> Array<out T>.find(predicate: (T) -> Boolean): T? {
return firstOrNull(predicate)
}
Sequence<T>.find
同上:
https://github.com/JetBrains/kotlin/blob/1.1.3/libraries/stdlib/src/generated/_Sequences.kt#L74
@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>.find(predicate: (T) -> Boolean): T? {
return firstOrNull(predicate)
}
(我自己不是 Kotlin 用户,但我很惊讶这些方法是作为为每个集合类型手动定义的编译时生成的代码实现的,而不是作为单个 JVM 泛型方法实现的——这有什么原因吗? ?)
关于collections - find 和 firstOrNull 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520267/
我需要映射一个列表并检索第一个非空元素,并且我需要像在 Java 8 流 API 中那样短路映射操作。在 Kotlin 中是否有现成的方法可以在没有 Java 8 流的情况下执行此操作? 为此,我创建
鉴于以下从 Kotlin Koans 中提取的代码: fun Shop.findAnyCustomerFrom(city: City): Customer? { // Return a cus
我是一名优秀的程序员,十分优秀!