One Off the Slack: Why Does fillMaxWidth() Not Work as a Default Value?

wenchao kong asked:

Hi, I had a question regarding default value for Modifier as a parameter, apparently fillMaxWidth is ignored if passed like this.

@Composable
fun TextButton(
    modifier: Modifier = Modifier.fillMaxWidth(),

Berkeli Alashov offered:

If you want to force fillMaxWidth:

@Composable
fun TextButton(
    modifier: Modifier = Modifier,
    ...
) {
    val defaultMod = Modifier.fillMaxWidth()
    InternalTextButton(
        modifier = modifier.then(defaultMod),
        ...
    )
}

Tad Fisher countered:

Or just modifier.fillMaxWidth()

This is perfectly idiomatic and is used throughout the Compose codebase.

Google’s Leland Richardson explained the difference:

yep. convention is to have the default expression just be modifier: Modifier = Modifier and then just start your modifier chain with that:

InternalTextButton(modifier = modifier.fillMaxWidth().etc(...)

note that the documents saying the first modifier parameter must: … are indicating what the convention is, not what is technically allowed/not allowed. what you wrote initially was perfectly valid kotlin, just not what you wanted 🙂


Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!