Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I idiomatically call a nullable lambda in Kotlin?

Tags:

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()
like image 696
Barry Fruitman Avatar asked Aug 07 '18 18:08

Barry Fruitman


People also ask

What is the idiomatic way to deal with nullable values referencing or converting them?

sure operator. The !! operator asserts that the value is not null or throws an NPE. This should be used in cases where the developer is guaranteeing that the value will never be null .

What is the correct way to initialize a nullable variable Kotlin?

Therefore you have to do the initialization var x : String? = null . Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String? . Alternatively you can use lateinit , also on non-nullable types.

What is the correct way to initialize a nullable variable?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.


2 Answers

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()     
 }
like image 160
Alexey Soshin Avatar answered Nov 01 '22 16:11

Alexey Soshin


Here is a simple example:

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

takeThatFunction { print("yo!") }
like image 39
Yunus Emre Avatar answered Nov 01 '22 16:11

Yunus Emre