目录
run()
fun testRun(): Unit {
println("xyz") // 直接调用println()函数
run({println("xyz")}) // 使用run()函数 调用println()函数
run { println("xyz") } // run()函数 的括号"()"可以省略
}
run()函数的定义:
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
最后一行 block()
是调用传入的参数 block
—— 通常是一个lambda表达式。
apply()
fun testApply(): Unit {
val la = ArrayList<String>().apply { // 使用apply()
add("x")
add("y")
add("z")
println("apply()_this = $this") // 输出:apply()_this = [x, y, z]
}
println(la) // 输出: [x, y, z]
val ls = mutableListOf<String>() // 普通写法
ls.add("x")
ls.add("y")
ls.add("z")
println(ls) // 输出: [x, y, z]
}
apply() 函数的定义:
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
最后两行代码,先调用了block()函数,后返回当前调用者this,意思是先执行block()代码的逻辑,再返回当前的调用者对象。
let()
val isOdd = {it: Int -> it %2 ==1}
val sum2 = fun (x: Int, y: Int):Int {return x + y}
fun testLet(): Unit {
12.let { println(it) } // 输出:12
println(12.let(isOdd)) // 输出:false
val re = sum2(2,9).let(isOdd)
println(re) // 输出:true
val strList = listOf("x","xy","xyz","xyz1","xyz12","xyz123","xyz1234")
strList.let { println(it) } // 输出:[x, xy, xyz, xyz1, xyz12, xyz123, xyz1234]
}
let() 函数的定义:
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
最后一行代码重点 block(this)
,把当前调用者对象 作为参数 传入block()函数。
also()
fun testAlso(): Unit {
val la = ArrayList<String>()
val re = la.also {
println(it) // 输出:[]
la.add("a1")
println(it) // 输出:[a1]
la.add("b1")
println(it) // 输出:[a1, b1]
}
println(la) // 输出:[a1, b1]
println(re) // 输出:[a1, b1]
}
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
}
最后两行代码,首先调用了 block(this),类似 let()
函数的逻辑,最后返回的是 this,即当前调用者对象。
with()
fun testWith(): Unit {
val la = ArrayList<String>()
with(la) {
add("x")
add("y")
add("z")
println("with()_this = $this") // 输出:with()_this = [x, y, z]
}.let { println(it) } // 输出:kotlin.Unit
println(la) // 输出: [x, y, z]
}
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()
}
with()函数传入了一个对象receiver,然后使用receiver对象去调用传入的lambda代码块,receiver.block() .
fun testWith2(): Unit {
val la = ArrayList<String>()
with(la) {
add("x")
add("y")
add("z")
println("with()_this = $this") // 输出:with()_this = [x, y, z]
5
}.let { println(it) } // 输出:5
println(la) // 输出: [x, y, z]
}