Home > Mobile >  Is it possible to call a lambda from another lambda?
Is it possible to call a lambda from another lambda?

Time:04-04

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related