【问题标题】:Most idiomatic way to prepend an element to a List ifNotEmpty() in Kotlin在 Kotlin 中将元素添加到 List ifNotEmpty() 的最惯用方式
【发布时间】:2020-01-31 04:22:26
【问题描述】:

我想在 List<Thing> 前面添加一个元素,但前提是列表不为空。

我在考虑takeIf { it.isNotEmpty() }orEmpty()flatMap 的组合。

在 Kotlin 中最惯用的方法是什么?

【问题讨论】:

  • 不需要花哨的东西:if (list.isEmpty()) list else listOf(e) + list。如果您不喜欢 list 重复,请使用此主体创建一个函数。

标签: list kotlin idioms


【解决方案1】:

这是我想出来的

val myEmptyList = listOf<String>()
val myNotEmptyList = listOf<String>("is", "the", "worst")

listOf("first").takeIf { myEmptyList.isNotEmpty() }.orEmpty() + myEmptyList
listOf("first").takeIf { myNotEmptyList.isNotEmpty() }.orEmpty() + myNotEmptyList

输出:

[]
[first, is, the, worst]

【讨论】:

    【解决方案2】:

    这里有一段代码非常地道,恕我直言:

    infix fun <T> Collection<T>?.prependIfNotEmpty(other: Collection<T>): Collection<T>? =
            if (this?.isNotEmpty() == true)
                other + this
            else
                this
    
    // or for non nullable lists your approach
    infix fun <T> Collection<T>.prependIfNotEmptyNonNull(other: Collection<T>): Collection<T> = other.takeIf { isNotEmpty() }.orEmpty() + this
    
    

    用法

    listOf(1, 2, 3) prependIfNotEmpty listOf(-1, 0) // [-1,0,1,2,3]
    
    listOf("two", "three", "four").prependIfNotEmpty(listOf("zero", "one")) // ["zero", "one", "two", "three", "four"]
    
    val list: List<Float>? = null
    
    list prependIfNotEmpty listOf(3.5, 5.6) // null
    
    //for prependIfNotEmptyNonNull the same usage
    

    也许有更惯用的方式,但我还没有弄清楚。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 2013-05-21
      • 2016-06-17
      • 2017-08-05
      • 2019-11-07
      • 2019-08-24
      相关资源
      最近更新 更多