Hello, I'm reading Compose guidelines and have a q...
# compose
g
Hello, I'm reading Compose guidelines and have a question. In the guidelines, there are rules:
Element functions MUST accept a parameter of type
Modifier
. This parameter MUST be named “`modifier`” and MUST appear as the first optional parameter in the element function's parameter list
and
Layout functions SHOULD use the name “`content`” for a
@Composable
function parameter if they accept only one
@Composable
function parameter.
Layout functions SHOULD use the name “`content`” for their primary or most common
@Composable
function parameter if they accept more than one
@Composable
function parameter.
Layout functions SHOULD place their primary or most common
@Composable
function parameter in the last parameter position to permit the use of Kotlin's trailing lambda syntax for that parameter.
So an example of the combination would be
Copy code
@Composable
fun FancyButton(
    text: String,
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit,
) {
What if my Composable accepts a modifier and a lambda? Should the lambda appears after or before modifier (given that it's not optional parameter)? My thinking is that I should move the lambda to the bottom of parameter list to leverage trailing lambda like:
Copy code
@Composable
fun FancyButton(
    text: String,
    modifier: Modifier = Modifier,
    onClick: () -> Unit,
) {
But in the guideline page, I often see
Copy code
@Composable
fun FancyButton(
    text: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
Can anyone explain the reason of having the lambda before the modifier?
f
If the lambda is after modifier, you cannot do
Copy code
FancyButton("hello", { print("world") })
and you will have to do
Copy code
FancyButton("hello", onClick = { print("world") })
g
but I can do this, right?
Copy code
FancyButton("hello") { print("world") }
f
Yeah but then it looks like the
print
is content of
FancyButton
g
I see. that makes sense. Thanks mate!
z
I would put the function param before the modifier in this case because, as a rule, I always use named parameters anyway when passing event handler functions. Since the convention is that trailing lambdas are content or factory functions, I find it a lot more readable for event handlers to be named. Makes it a lot more obvious what the actual event being handled is.