Reputation: 12656
Given the following lambda:
val lambda: () -> Unit = null
Which of the following calls is idomatic to Kotlin for calling a nullable lambda?
lambda?.let { it() }
vs
lambda?.invoke()
Upvotes: 25
Views: 10906
Reputation: 419
Here is a simple example:
fun takeThatFunction(nullableFun: (() -> Unit)?) {
nullableFun?.let { it() }
}
takeThatFunction { print("yo!") }
Upvotes: 2
Reputation: 17691
Let's ask Kotlin compiler:
val lambda: (() -> Unit)? = null
lambda()
Compilers says:
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.
Although even this seems fine by me (and by compiler too):
if (lambda != null) {
lambda()
}
Upvotes: 45