我刚接触 Kotlin 大约 2 周,我一直对函数式编程非常感兴趣,我不确定在这部分我是否错过了 FP 中的基本习语,因为我想处理样板,例如从存储库中检索结果,如果结果是一个空列表然后我想要一个日志语句并希望其他链接调用停止。一般来说,为什么(至少对我来说不明显)没有处理空列表的函数?像下面?问这个问题,我可能会省略“这个”空检查。
fun <E : Any, T : List<E>> T?.ifEmpty(func: () -> Unit): List<E> {
if (this == null || this.isEmpty()) {
func()
return emptyList()
}
return this
}
fun <E : Any, T : List<E>> T?.ifNotEmpty(func: (List<E>) -> Unit): List<E> {
if (this != null && !this.isEmpty()) {
func(this)
return this
}
return emptyList()
}
fun <E : Any, F: Any, T : List<E>> T?.mapIfNotEmpty(func: (List<E>) -> (List<F>)): List<F> {
if (this != null && !this.isEmpty()) {
return func(this)
}
return emptyList()
}
最佳答案
ifEmpty 自 Kotlin 1.3 (kotlin.collections) 起可用。
ifNotEmpty
看起来像无用的函数,我们经常遍历列表,如果列表为空,我们的代码将不会执行。所以,例如
list.ifNotEmpty { do sth with whole list. sth like iteration? mapping? }
效果和
一样list.forEach { do sth with only one element and nothing if list is empty }
list.map { map every element to other object }
如果还不够,你可以这样写:
list.takeIf { it.isNotEmpty() }?.apply|let // unfortunately it looks ugly
mapIfNotEmpty 同样的故事,例如
listOf<String>("ab", "cd").mapIfNotEmpty { it.reversed() } listOf<String>("ab", "cd").map { it.reversed() }
有完全相同的结果。
关于generics - 处理惯用函数链中的空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876167/