Mattia Ferigutti
Mattia Ferigutti

Reputation: 3708

Is it possible to call a lambda from another lambda?

I'm trying to call a lambda from another lambda in this way:

fun fetch(
  onSuccess: (result: Any, onSet: () -> Unit) -> Unit
) {
  remoteConfigInstance.fetchAndActivate()
    .addOnCompleteListener { task ->
      if (task.isSuccessful) onSuccess(task.result, ()) // <- Here is the issue 
    }
}

I get an error trying to call the onSet lambda like this. Is there a correct approach to solve this problem?

Upvotes: 1

Views: 83

Answers (2)

a_local_nobody
a_local_nobody

Reputation: 8191

The answer pointed out here is entirely correct, just as a potential way of improving your code, consider the following option:

fun fetch(
        onSuccess: (result: Any, onSet: (() -> Unit)? ) -> Unit) {
        remoteConfigInstance.fetchAndActivate()
            .addOnCompleteListener { task ->
            if (task.isSuccessful) onSuccess(task.result, null) // <- here you can now pass null, instead of an actual empty lambda
            }
    }

which allows you to instead make use of null if you don't want to do anything

Upvotes: 1

Ivo
Ivo

Reputation: 23164

the problem is simply that () is not a lambda. Replace it with {}

Upvotes: 3

Related Questions