Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 743 Vote(s) - 3.58 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I idiomatically call a nullable lambda in Kotlin?

#1
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()
Reply

#2
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()
}
Reply

#3
Here is a simple example:

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

takeThatFunction { print("yo!") }
Reply

#4
An alias on this case could be a more expressive approach

```
typealias TheNameOFYourCallback = ()-> Unit

class Something {

private var callback: TheNameOFYourCallback? = null

fun setTheCallback(callback: TheNameOFYourCallback) {
this.callback = callback
}

private fun usageOfCallback() {
callack?.invoke()
}

}
```

And then for using

```
val something = Something()
something.setTheCallback {
//Do your thing
}
```

Off course, the `var` could have been not `private` but in this way setting the callback can take advantage of the syntactic sugar of lambdas for methods, otherwise, the assignation form seems odd to me, judge by your self:

```
something.callback = {
//Do your thing
}
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through