https://kotlinlang.org logo
#compose
Title
# compose
v

Vinay Gaba

12/20/2020, 2:11 AM
I encountered a lint rule that doesn’t allow me to pass a custom default modifier to a method and instead recommends that I simply use the default
Modifier
Copy code
// Not allowed
fun TestComponent(
    modifier: Modifier = Modifier.fillMaxWidth().preferredSizeIn(maxHeight = 200.dp)
)

// Instead, it recommends that you do this
fun TestComponent(
    modifier: Modifier = Modifier
)
Could someone shed some more light on why this is a guideline? Since this is intentionally enforced, I’m sure there is a very good reason to do this. It’s obviously more reusable which makes complete sense but I wonder if this is one place where it would be okay to have some flexibility.
a

Adam Powell

12/20/2020, 2:24 AM
Why should the sizing behavior change if I call
Copy code
TestComponent(Modifier.background(Color.Blue))
as opposed to
Copy code
TestComponent()
?
v

Vinay Gaba

12/20/2020, 2:26 AM
💡 That makes a lot of sense! I guess I was looking at it from a very use case specific pov but I can see why this is actually valuable! Thanks!
a

Adam Powell

12/20/2020, 2:26 AM
🙂
Instead consider defining these kind of default size parameters using the
preferred
size modifiers chained off of the modifier you receive as a parameter, e.g.
Copy code
@Composable fun TestComponent(
  modifier: Modifier = Modifier
) = Row(
  modifier.fillMaxWidth()
    .preferredSizeIn(maxHeight = 200.dp)
) {
  // contents
}
if the incoming constraints don't permit sizing to the preferred sizes, the incoming constraints will win
v

Vinay Gaba

12/20/2020, 2:38 AM
Yeah I ended up chaining it to get around the lint error.
if the incoming constraints don't permit sizing to the preferred sizes, the incoming constraints will win
- This is assuming the incoming constraints are more restrictive than
maxHeight = 200.dp
a

Adam Powell

12/20/2020, 2:39 AM
yes; though
height(250.dp)
is also more restrictive; the incoming
min
can cause a preferred
max
downstream to be overridden
v

Vinay Gaba

12/20/2020, 2:40 AM
ah I see! 🎖️
4 Views