继续来看一下kotlin中run函数的应用,首先看一下源码:
/**
* Calls the specified function [block] and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#run).
*/
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
从run函数的使用上来说,他更近似于let和with函数的结合体,我们前面说过,let函数可以先行判空,然后再调用,但在函数体内还是需要使用it来指代调用者(let函数的学习使用可以参考前面文章 Android kotlin let函数学习)。而with函数没有先行判空,但好处是可以再函数体内直接使用传入参数的方法和变量等(with函数的学习使用可以参考前面文章 Android kotlin with函数学习)。
我们可以看到,let和with函数都有其自身的优缺点,而r