How can I pass paramters to the fun CompositionLocalProvider(vararg values: ProvidedValue<*>,...) in Android Studio?

Viewed 84

The Code A is the source code of Android Studio.

The Code B is from the offical sample project here.

I can't understand fully why the author can pass these paramters LocalContentAlpha provides ContentAlpha.medium to the function CompositionLocalProvider((vararg values: ProvidedValue<*>, ...).

You know that we separate paramters with comma normally.

Code A

@OptIn(InternalComposeApi::class)
fun CompositionLocalProvider(vararg values: ProvidedValue<*>, content: @Composable () -> Unit) {
    currentComposer.startProviders(values)
    content()
    currentComposer.endProviders()
}

Code B

 CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
                Text(
                    text = stringResource(
                        id = R.string.article_post_min_read,
                        formatArgs = arrayOf(
                            metadata.date,
                            metadata.readTimeMinutes
                        )
                    ),
                    style = typography.caption
                )
            }
1 Answers

The sample uses infix function which allows to use alternative notation for invoking a function - without a dot and parentheses. You can translate the above code to:

LocalContentAlpha.provides(ContentAlpha.medium)

CompositionLocalProvider in this example actually receives only a single ProvidedValue<*> parameter, which is returned by this provides() function.

You can read about provides() function here. As you can see, it has infix modifier.

Related