Kotlin 列表中 plus() 与 add() 的区别

Vin*_*ena 5 kotlin

我是 Kotlin 的新手。我想知道 Kotlin List 中 plus() 和 add() 的区别。

Sim*_*ant 10

fun main() {
    val firstList = mutableListOf("a", "b")
    val anotherList = firstList.plus("c") // creates a new list and returns it. firstList is not changed
    println(firstList) // [a, b]
    println(anotherList) // [a, b, c]

    val isAdded = firstList.add("c") // adds c to the mutable variable firstList
    println(firstList) // [a, b, c]
    println(isAdded) // true

    val unmodifiableList = listOf("a", "b")
    val isAdded2 = unmodifiableList.add("c") // compile error, add is not defined on an UnmodifiableList
}
Run Code Online (Sandbox Code Playgroud)

plus从现有列表和给定项目或另一个列表中创建一个新列表并返回结果(新创建的列表),而输入列表永远不会更改。该项目不会添加到现有列表中。

add只在可修改的列表上定义(而 Kotlin 中的默认值是 ImmutableList),并将项目添加到现有列表中,并返回true以指示项目已成功添加。


P.J*_*uni 5

基本上:

plus() 添加元素并返回包含此新值的列表。

返回一个列表,其中包含原始集合的所有元素,然后是给定的 [element]。

所以用plus()

val list1 = listOf(1,2,3)
val list2 = list1.plus(4) // [1, 2, 3, 4]
val list3 = listOf(0).plus(list2) // [0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

add() 只需添加一个元素并返回 bool。

将指定的元素添加到此列表的末尾。返回true是因为列表总是作为此操作的结果被修改。