Barry Fruitman
Barry Fruitman

Reputation: 12656

How do I idiomatically call a nullable lambda in Kotlin?

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

Answers (2)

Yunus Emre
Yunus Emre

Reputation: 419

Here is a simple example:

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

takeThatFunction { print("yo!") }

Upvotes: 2

Alexey Soshin
Alexey Soshin

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

Related Questions