run():执行调用传入方法
//方法定义
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
method()
run({method()})
run{method()}
//以上三个方法等价
apply():执行调用传入方法并返回调用者本身
//方法定义
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
list<String>.apply({
it.add("a")
it.add("b")
})
list = {"a","b"}
let():将调用者作为传入方法的参数执行
//方法定义
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
"abc".let{println(it)}
//输出"abc"
also():将调用者作为参数传入方法执行并返回调用者
//方法定义
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
val a = "ABC".also {
println(it) //输出:ABC
}
println(a)//输出:ABC
with():使用传入的参数调用传入的方法
//方法定义
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
网友评论