Home > Mobile >  Which parameter is applied when there are serveal lambda variables in a function?
Which parameter is applied when there are serveal lambda variables in a function?

Time:10-20

Normally, when the latest parameter of a function is a lambda , I can use such as function(first,...) {latest} to pass the lambda parameter.

The Code A and Code B are from the official sample project.

There are three lambda parameters in fun NiaFilledButton which are text, leadingIcon and trailingIcon in Code A.

When the author invoke the function with Code B, which parameter will be assigned with the value of Text(text = "Enabled") ?

Code A

@Composable
fun NiaFilledButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    small: Boolean = false,
    colors: ButtonColors = NiaButtonDefaults.filledButtonColors(),
    text: @Composable () -> Unit,
    leadingIcon: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null
) {
   ...
}

Code B

NiaFilledButton(onClick = {}) {
   Text(text = "Enabled")
}

CodePudding user response:

When you pass a lambda argument outside of parentheses, it's always the last argument to the function. This is true regardless of what other arguments you pass inside the parentheses, named or otherwise. You can only use the trailing lambda syntax when the last argument is a function.

That means that your Code B will pass the lambda as trailingIcon.

You can read more in the docs for passing trailing lambdas.

CodePudding user response:

For things like this Kotlin Playground is useful.

fun main() {
    foo(o= { println("o")} ) { println("b") }
}

fun foo(
    o: () -> Unit,
    b: (() -> Unit)? = null,
    c: (() -> Unit)? = null
) {
    o()
    c?.invoke()
}

The output is o b because is the last and compile won't allow you to use more than one non-parenthesized argument.

  • Related