Is there a way to limit the number/types of components in a composable and to make the compiler complain about it (i.e. compile error, not runtime)?
Say for instance, that I have my own Button implementation where I only want to allow first one Icon and then one Text, in that order.
j
jim
06/26/2021, 5:05 PM
You could have your button take in a
vectorIcon
and a
String
, and have the button be responsible for emitting the appropriate child widgets, instead of taking in a generic children lambda which is relatively unconstrained.
☝️ 3
➕ 3
c
Colton Idle
06/26/2021, 5:09 PM
Yeah. That's what we do. We constrain what can go into our design systems button.
j
Jimmy
06/26/2021, 5:10 PM
Right, a button was only an example, but I get what you mean.
Feels like it's not the compose way though, had hoped there would be some magic under the hood that could be used.
c
Colton Idle
06/26/2021, 5:11 PM
It's just a function. So to me it seems like the compose way would be to use the language to your advantage.
☝️ 2
j
Jimmy
06/26/2021, 5:15 PM
True, but composing views with the lambdas make the code look neat. So it's not just a function, it's a good looking function 😄
But I guess I'll do something like that. Thanks.
t
Timo Drick
06/29/2021, 2:18 PM
Maybe an other more convient way is to provide a scope with a DSL that only have specific composables included:
Copy code
interface RestrictedContentScope {
@Composable fun CompanyButton()
@Composable fun CompanyText()
}
@Composable
fun RestrictedContent(content: RestrictedContentScope.() -> Unit) {
val scope = object : RestrictedContentScope {
override fun CompanyButton() {
Button(onClick = {}) {
//...
}
}
override fun CompanyText() {
Text("")
}
}
content(scope)
}
Please note that the content is not a composable so it is here restricted to use custom composables.