Kotlin中的集合明确区分了可变集合和不可变集合
List<T>
只提供了size
,get
这些只读的方法,MutableList<T>
提供了修改List的方法。同样有Set<T>/MutableSet<T>
和Map<K, V>/MutableMap<K, V>
val numbers: MutableList<Int> = mutableListOf(1, 2, 3)
val readOnlyView: List<Int> = numbers
println(numbers) // prints "[1, 2, 3]"
numbers.add(4)
println(readOnlyView) // prints "[1, 2, 3, 4]"
readOnlyView.clear() // -> does not compile
val strings = hashSetOf("a", "b", "c", "c")
assert(strings.size == 3)
创建集合的方法:
- listOf
- mutableListOf
- setOf
- mutableSetOf
- mapOf(a to b, c to d)
list的toList
方法返回当前list的快照
class Controller {
private val _items = mutableListOf<String>()
val items: List<String> get() = _items.toList()
}
List的一些其他方法
val items = listOf(1, 2, 3, 4)
items.first() == 1
items.last() == 4
items.filter { it % 2 == 0 } // returns [2, 4]
val rwList = mutableListOf(1, 2, 3)
rwList.requireNoNulls() // returns [1, 2, 3]
if (rwList.none { it > 6 }) println("No items above 6") // prints "No items above 6"
val item = rwList.firstOrNull()