gpt4 book ai didi

collections - find 和 firstOrNull 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 13:32:10 31 4
gpt4 key购买 nike

鉴于以下从 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 工作人员讨论了不同方法的优点 findfirstOrNull :

https://youtrack.jetbrains.com/issue/KT-5185

虽然不是官方声明,但 JetBrains 的员工 Ilya Ryzhenkov 将其描述为:

I think we can undeprecate find and make it an alias to firstOrNull. Much like indexOf 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 use firstOrNull, 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com