gpt4 book ai didi

kotlin - Kotlin继续进行 map 操作

转载 作者:行者123 更新时间:2023-12-02 12:39:04 25 4
gpt4 key购买 nike

我正在尝试使用一系列过滤器和映射调用来转换列表。过滤逻辑再次用于 map 调用中,我想避免重复调用。我认为代码总结得很好:

fun main(args: Array<String>) {
multipleCalls()
wontCompile()
}

fun multipleCalls(){
val arr = intArrayOf(1,2,3)
val list = arr.filter{
it.heavyLogic() != null
}.map{
it.heavyLogic() //heavyLogic() called again
}
print(list)
}

fun wontCompile(){
val arr = intArrayOf(1,2,3)
val list = arr.map{
val str = it.heavyLogic()
if(str == null) continue //break and continue are only allowed inside a loop
else str
}
print(list)
}

map 中是否有等效的break / continue可以修复 wontCompile()

我意识到我也可以让 map返回 null,从而使 list的类型为 List<String?>-然后通过 filter生成 null。但这仍然使列表重复两次。

最佳答案

您可以使用mapNotNull

inline fun <T, R : Any> Array<out T>.mapNotNull(
transform: (T) -> R?
): List<R> (source)

I realize I can also have map return nulls, thereby making list of type List - and then filter by null. But that still iterates the list twice.



通过使用 mapNotNull,列表只需迭代一次,在此期间将忽略空项目。
/**
* Applies the given [transform] function to each element in the original collection
* and appends only the non-null results to the given [destination].
*/
public inline fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapNotNullTo(destination: C, transform: (T) -> R?): C {
forEach { element -> transform(element)?.let { destination.add(it) } }
return destination
}

在您的代码中,您可以执行以下操作:
val list = arr.mapNotNull{
it.heavyLogic()
}

您还可以检查有关 filterNotNull的信息。

关于kotlin - Kotlin继续进行 map 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52307142/

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