小编117*_*174的帖子

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

我刚接触 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 …
Run Code Online (Sandbox Code Playgroud)

generics kotlin

2
推荐指数
1
解决办法
1018
查看次数

标签 统计

generics ×1

kotlin ×1