How do I idiomatically call a nullable lambda in Kotlin?

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()     
 }

Here is a simple example:

fun takeThatFunction(nullableFun: (() -> Unit)?) {
    nullableFun?.let { it() }
}

takeThatFunction { print("yo!") }

Tags:

Kotlin