Why was I warned "Optional Modifier parameter should have a default value of Modifier" in Jetpack Compose?

Viewed 72

I get the following warning information with Code A, why?

Optional Modifier parameter should have a default value of Modifier

Code A

@Composable
fun DisplayIcon(
    modifier: Modifier=Modifier.size(24.dp),
    icon: ImageVector,
    tint: Color = Color.Blue
) {
    Icon(icon, null, modifier = modifier, tint = tint)
}
1 Answers

It's just a best practice. Using some other default value might lead to weird situations - imagine you want to use two of this component in a Column:

Column {
    DisplayIcon()
    DisplayIcon()
}

Everything's fine, but now you want to align one of them:

Column {
    DisplayIcon()
    DisplayIcon(modifier = Modifier.align(Alignment.End))
}

And suddenly, with no apparent reason, one has different size than the other. So you have to find out from DisplayIcon implementation what's going on, and then probably add .size(24.dp) to your aligned composable as well. But now you want to change the default size, and you have to do so on many different places...
Something like this might be better solution:

@Composable
fun DisplayIcon(
    modifier: Modifier = Modifier,
    icon: ImageVector,
    tint: Color = Color.Blue,
    size: Dp = 24.dp,
) {
    Icon(icon, null, modifier = modifier.size(size), tint = tint)
}
Related