我是 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
以指示项目已成功添加。
基本上:
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
是因为列表总是作为此操作的结果被修改。
归档时间: |
|
查看次数: |
2737 次 |
最近记录: |