kotlin apply also
功能:调用某对象的apply函数,在函数块内可以通过 this 指代该对象。返回值为该对象自己。
val a = "string".apply {
println(this)
}
println(a)
string
string
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }
功能:调用某对象的also函数,则该对象为函数的参数。在函数块内可以通过 it 指代该对象。返回值为该对象自己。
val a = "string".also {
println(it)
}
println(a)
string
string
also 把调用对象当参数传入, apply是调用对象的方法 所以also能处理的更多
浙公网安备 33010602011771号