内置函数 | 持有值 | 返回值 | 异同点 | 使用场景 |
---|---|---|---|---|
T.apply | this | this | ||
T.also | it | this | ==apply,持有值不同 | |
T.let | it | return | 判空+空合并操作符 | |
T.run | this | return | ||
with(T) | this | return | ==run,调用方式不同 | |
takeIf | it | ture=this false=null | 空合并操作符 | |
takeUnless | it | ture=null false=this | takeIf相反 | 空合并操作符+string.isNullOrBlack |
apply
fun <T> T.myApply(action: T.() -> Unit): T {
//持有this ,return this
this.action()
return this
}
let
fun <T, R> T.myLet(action: (T) -> R): R {
//持有it ,return this.action(it)类型
return action(this)
}
run
fun <T, R> T.myRun(action: T.() -> R): R {
//持有this ,return this.action()类型
return this.action()
}
also
fun <T> T.myAlso(action: (T) -> Unit): T {
//持有it ,return this
action(this)
return this
}
with
fun <T, R> myWith(ob: T, action: T.() -> R): R {
//持有ob = this ,return ob.action()类型
return ob.action()
}
takeIf
fun <T> T.myTakeIf(action: (T) -> Boolean): T? {
//持有it ,return this.action(it) = [true this类型 ,false null类型]
val isTrue = action(this)
return if (isTrue) this else null
}
takeUnless
fun <T> T.myTakeUnless(action: (T) -> Boolean): T? {
//持有it ,return this.action(it) = [false this类型 ,true null类型]
val isTrue = action(this)
return if (!isTrue) this else null
}
其他
fun <T> T.myTake(action: (T) -> Boolean): Boolean {
//持有it,return this.action(it)的boolean类型
return action(this)
}
fun <T, R> T.myCustom(action: T.(T) -> R): R {
//持有this ,return action(this)类型
return this.action(this)
}