generics - 处理惯用函数链中的空列表

标签 generics kotlin

我刚接触 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/

相关文章:

java - 在嵌套的 java Spring 配置属性类中,可以使用父级的值来初始化子级吗?

button - libgdx按钮向上向下没有作用

java - @GlideOption 添加/扩展 RequestBuilder 来自定义监听器并实现 Java 8 中的功能方法

java - 在@Transactional方法调用期间,初始化期间Bean属性不为null

swift - 嵌套函数使 Swift 编译器崩溃

c# - 如何在 C# 中正确设计通用接口(interface)及其非通用接口(interface)?

java - 如何修复 'Unchecked cast from MyClass to T'

java - 如何实现扩展 Comparable 的列表列表?

android - Kotlin 全局变量显示为零 "0"

c# - 如何遍历通用 List<T> 并按 3 项进行分组