集合
List
listOf
不能添加和修改元素
只能读,不可写
val list = listOf(1, 2, 3)
底层是kotlin封装的Collections.kt下的List,不是java.util.List类型
没有add,set方法
public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList()
mutableListOf
可读写的集合
val list1 = mutableListOf(1, 2, 3)
list1.add(5)
list1[2] = 10
list1.forEach { println(it) }
返回的是kotlin中的ArrayList,这个ArrayList的父类是MutableList
底层是MutableList,有读写的方法
public fun <T> mutableListOf(vararg elements: T): MutableList<T> =
if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
arrayListOf
与mutableListOf一致
返回ArrayList,底层还是引用了java的ArrayList
public fun <T> arrayListOf(vararg elements: T): ArrayList<T> =
if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
Set
setOf
只读集合
mutableSetOf
可读写集合
没有修改的方法
Map
mapOf
只读集合
val map = mapOf(1 to 1)
mutableMapOf
可读写集合
mutableMapOf(1 to 1)
hashMapOf
可读写集合
hashMapOf(1 to 1)
遍历
for ((k,v) in hashMap){
}
hashMap.forEach { t, u ->
}
hashMap.forEach{entry ->
}
五大函数
apply
任意类型都有apply扩展函数
lambda表达式有this作用域
可以访问当前对象的方法
函数返回值时调用者本身
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
let
任意对象都有let扩展函数
let函数参数也高阶函数
高阶函数参数也是调用者本身
函数的返回值是高阶函数的返回值
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
val s:Boolean = list.let {
""
1
true//返回值
}
with
独立函数,可以在任意地方调用
接收两个参数,第一个参数是任意类型,第二个是函数参数,拥有此第一个参数类型的作用域
返回值是函数参数的返回值
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
val b= with("hh"){
var b=false
if (this.startsWith("h")){
b=true
}
b
}
run
任意类型都有run扩展函数
有一个函数参数,拥有调用者本身的作用域
返回值是函数参数的返回值
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
val bb = "".run {
true
}
also
任意对象的扩展函数
接收一个函数参数,函数参数的参数是调用者本身
返回值是调用者本身
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}