- Kotlin let,run,with,also,apply 函
- Kotlin(let,with,run,apply,also)函
- let also run with apply选择太多?教你怎么
- 掌握Kotlin标准函数:run, with, let, als
- 更好的理解 Kotlin 标准函数 let、apply、also
- Kotlin的五个高阶函数with/also/apply/let
- Kotlin标准库函数: run,let,also,apply,
- kotlin中 run、apply、let、also、with
- Kotlin学习笔记(2):run、apply、let、also
- 【转载】Kotlin系列之let、with、run、apply、
let
- 是扩展函数;
- 作为扩展函数,把自己作为参数传递进去,(T);
- 可以在作用域范围内使用it作为引用;
- 返回不同类型的值。
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
run
- 是扩展函数;
- 作为扩展函数调用block: T.()
- 所有的范围内,T可以被称为this;
- 返回不同类型的值。
public inline fun <T, R> T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
also
- 是扩展函数;
- 作为扩展函数,把自己作为参数传递进去,(T);
- 可以在作用域范围内使用it作为引用;
- 返回T本身即this。
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
with
- 不是扩展函数;
- 所有的范围内,T可以被称为this;
- 返回不同类型的值。
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
apply
- 是扩展函数;
- 作为扩展函数调用block: T.()
- 所有的范围内,T可以被称为this;
- 返回T本身即this。
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
网友评论