kotlin apply 和 also 的差别
2019-08-27 本文已影响0人
professorHe
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#apply).
*/
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
/**
* Calls the specified function [block] with `this` value as its argument and returns `this` value.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#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
}
also 和 apply的差别主要存在于,lambda表达式内context表示方式,also是通过传入 的参数(it)来表示的,而apply是通过this来表示的。
also 可用于不更改对象的其他操作,例如记录或打印调试信息。通常,您可以在不破坏程序逻辑的情况下从调用链中删除也是调用。
val numbers = mutableListOf("one", "two", "three")
numbers.also { println("The list elements before adding new one: $it") }
.add("four")
apply主要对接收器对象的成员进行操作。 apply的常见情况是对象配置。此类调用可以读作“将以下赋值应用于对象"
val adam = Person("Adam").apply {
age = 32
city = "London"
}