24

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()
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135
  • 2
    This is gonna be up for personal opinions, but to give mine, the `let` usage here looks completely unnecessary, I always use just `?.invoke()`. – zsmb13 Aug 07 '18 at 19:08
  • 3
    If we're onto personal opinions, why not just make the lambda non-null and say `() -> Unit = {}`? – EpicPandaForce Aug 07 '18 at 20:50

2 Answers2

40

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()     
 }
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
2

Here is a simple example:

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

takeThatFunction { print("yo!") }
Yunus Emre
  • 390
  • 3
  • 9