HelloCW
HelloCW

Reputation: 2255

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

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")
}

Upvotes: 1

Views: 68

Answers (2)

Sam
Sam

Reputation: 9944

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. You can read more in the docs for passing trailing lambdas.

That means that your Code B will try to pass the lambda as trailingIcon. With your code A, this doesn't compile, because as you pointed out in a comment, there's no value provided for the required parameter text. In the sample project you linked to, there's actually an additional overload for the function which does not require the text parameter. That's why the function call shown in your Code B is valid.

Upvotes: 3

TheLibrarian
TheLibrarian

Reputation: 1888

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.

Upvotes: 0

Related Questions