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()
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 .
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.
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.
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!") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With