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

Jan Skrasek

05/20/2022, 7:02 AM
API design: I have rather complex composable component taking multiple slots arguments. Is it better to have: • main slot named
content
and having it as the last one, or • make that slot rather named by its function and sort slots differently? The second option seems more suitable, but only if there is another non slot argument as the last one, otherwise it would expose the last slot as trailing lambda, which is not good. What do you think?
s

Stylianos Gakis

05/20/2022, 7:05 AM
I’d be very surprised if I used a composable, which had many composable slots but the one that was put in the trailing lambda was not the “main” one. I would say take inspiration from ones like
Scaffold
and don’t steer away from that pattern. You can still name your “content” one differently I guess, but I’d still like it to be last.
Like this sort of code on the call site
Copy code
Scaffold(
    topBar = { TopAppBar() },
    content = { FooScreen() }
) {
    // this would be the parameter named `bottomBar` as the last one in line
    BottomAppBar()
}
Would be super confusing in my opinion.
j

Jan Skrasek

05/20/2022, 7:11 AM
What I have is something like this
Copy code
ListChoice(
     onClick = {},
     icon = { Icon(Icons.Accommodation, contentDescription = null) },
     description = { Text("Further description") },
     trailingIcon = { Icon(Icons.ChevronRight, contentDescription = null) },
 ) {
     Text("ListChoice title")
 }
And we're thinking about if keep it this way with content, or name it
title
and put it before icon parameter.
Slots are optional expect the title slot, so in this case it could be quite good to utilize trailing lambda. Though practically it won't be used without other slots.
s

Stylianos Gakis

05/20/2022, 7:13 AM
Could you show me how the
ListChoice
function signature looks like?
j

Jan Skrasek

05/20/2022, 7:16 AM
Copy code
@Composable
public fun ListChoice(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    icon: @Composable () -> Unit = {},
    description: @Composable () -> Unit = {},
    trailingIcon: @Composable () -> Unit = {},
    withSeparator: Boolean = true,
    content: @Composable () -> Unit,
)
s

Stylianos Gakis

05/20/2022, 7:43 AM
This reminds me of ListItem a lot, which is basically what you’re doing, but with your defaults instead of the Material ones. You can draw inspiration from there and just rename the
content
to
text
or something similar as you said before, and still keep it as the last item without a default value. I think then the API will look nice and will be very predictable for all devs trying to use it.
j

Jan Skrasek

05/20/2022, 7:52 AM
Great idea, I somehow missed there is a ListItem in Material! Thank you very much.
🙌 1
5 Views