Given the following lambda:
val lambda: () -> Unit = null
以下哪项调用对于Kotlin调用可为空的lambda是idomatic的?
lambda?.let { it() }
vs
lambda?.invoke()
Given the following lambda:
val lambda: () -> Unit = null
以下哪项调用对于Kotlin调用可为空的lambda是idomatic的?
lambda?.let { it() }
vs
lambda?.invoke()
Let's ask Kotlin compiler:
val lambda: (() -> Unit)? = null
lambda()
编译器说:
Reference has a nullable type '(() -> Unit)?', use explicit '?.invoke()' to make a function-like call instead
So yeah, seems that ?.invoke()
is the way to go.
尽管我(以及编译器)觉得这也不错:
if (lambda != null) {
lambda()
}