with
with以某一对象作为参数,在函数块内通过this指代该对象; 函数块内可以直接调用对象的方法或者属性。
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
apply
apply函数指在函数块内可以通过this指代改对象,返回值为该对象自己。在链式调佣中,可以考虑使用它,从而不用破坏链式。
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
val result ="Jr".apply {
println(this+" Yang")
this+" Yang" // apply 会返回该对象自己,所以 result 的值依然是“Jr”
}
println(result)
执行结果:
Jr Yang
Jr
run
run类似于apply函数,但是run函数返回的是最后一行的值
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
相同的例子
val result ="Jr".run {
println(this+" Yang")
this+" Yang" // apply 会返回该对象自己,所以 result 的值依然是“Jr”
}
println(result)
执行结果:
Jr Yang
Jr Yang
let
let函数把当前的对象作为闭包的it参数,返回值是函数里面最后一行,或者指定return。它类似run函数
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
通常情况下,let 函数跟?结合使用:
params?.let {
......
}
also
also类似于apply的功能。但是also的函数块内可以通过it指代该对象,返回值为该对象它自己。
@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
}
val result ="Jr".apply {
println(this+" Yang")
this+" Yang" // apply 会返回该对象自己,所以 result 的值依然是“Jr”
}
println(result)
执行结果:
Jr Yang
Jr
如何选择
graph TD
A(如何选择) --> B{是否需要该对象本身}
B --> |需要| C{传递it/this作为参数}
B --> |不需要| D{是否需要扩展函数}
C --> |传递this| E[T.apply]
C --> |传递it| F[T.also]
D --> |需要| G{传递it/this作为参数}
D --> |不需要| H{传递it/this作为参数}
G --> |传递this| I[T.run]
G --> |传递it| J[T.let]
H --> |传递this| K[with]
H --> |传递it| M[run]
E --> N(结束)
F --> N
I --> N
J--> N
K --> N
M --> N