集合:List, Set, Map
Kotlin官网:Other-Collections
Kotlin区分只读集合和可变集合。
可变集合和只读集合都可以声明为只读,用起来也相同。
Kotlin的List<out T>
只提供只读操作,类似size, get之类的函数,继承自Collection<T>
和Iterable<T>
接口。对于可变List有MutableList<T>
接口,Set<out T>/MutableSet<T>
和Map<K, out 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)
Kotlin标准库中有创建集合的函数,例如listOf()
, mutableListOf()
, setOf()
, mutableSetOf()
。对于对性能不敏感的map的简单创建方式:mapOf(a to b, c to d)
。
声明为只读集合,但指向一个可变集合,依然是可变的。如果唯一一个指向集合的引用也是只读的,则认为集合是完全只读的。举个例子:
val items = listOf(1, 2, 3)
目前listOf方法是用array list实现的,未来会针对内存优化成完全只读的集合实现。
只读集合的类型是可以继承的,例如List<Rectangle>
可以赋值给List<Shape>
,Rectangle类继承自Shape类,认为两个集合是继承的,可变集合则不行,具体详见3-8泛型。
如果想返回一个集合当前状态的副本并保证集合改变时,这个副本依然保持当时的状态不变:
lass Controller {
private val _items = mutableListOf<String>()
val items: List<String> get() = _items.toList()
}
toList
扩展方法复制了集合元素,保证函数返回的集合在原集合改变时依然不变。
建议熟悉以下常用集合扩展方法;
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()
一些常用工具方法例如sort, zip, fold, reduce等等不再赘述。
Map和List整体差不多,使用如下:
val readWriteMap = hashMapOf("foo" to 1, "bar" to 2)
println(readWriteMap["foo"]) // prints "1"
val snapshot: Map<String, Int> = HashMap(readWriteMap)