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

Nacho Ruiz Martin

07/25/2021, 10:49 AM
👋 Is there a better way to "inherit" from a Composable than redeclaring all the parameters of the inherited? I want to extend the functionality of some Material composables with custom logic that I don't want to repeat everywhere.
c

CLOVIS

07/25/2021, 10:58 AM
I guess you could always declare an interface for the Composable?
Something like
interface MyComposable : @Composable (Int, Int, String) -> Unit
Not 100% sure that works
n

Nacho Ruiz Martin

07/25/2021, 11:04 AM
🤔 I can’t see the use case of it. How would I then make the call to the Material composable? I’m talking not having to redeclare all parameters in something like:
Copy code
@Composable
fun MyTextField(
    val value: String,
    val onValueChange,
    ...
) {
    TextField(
        value = value,
        ...
    )
}
c

Chrimaeon

07/25/2021, 11:35 AM
The design pattern that Compose uses it „Composition over inheritance“. That’s why Composables are functions and not classes. So the answer to your question: yes, you have to redeclare all parameters that your custom Composable uses.
☝️ 5
n

Nacho Ruiz Martin

07/25/2021, 11:35 AM
Ok! That’s what I was expecting, but maybe you pros had a cool Kotlin-ized way to do it 🙂. Thanks!
z

Zun

07/25/2021, 1:40 PM
I guess this is an opportunity for a plug-in that auto generates the parameters you have to redeclare with appropriate default values (or am I being too lazy?)
🤔 1
n

Nacho Ruiz Martin

07/25/2021, 2:57 PM
It’d be really good, to be honest.
d

Dominaezzz

07/25/2021, 4:37 PM
Good luck with binary compatibility though.
c

CLOVIS

07/25/2021, 4:55 PM
@Zun there's a proposal somewhere to create a
dataarg
modifier that adds all the parameters of a data class' constructor to that function if you really want to make a plugin, that essentially solves this problem and can be useful in many other places as well
The ‘real’ Compose answer though is probably something like ‘it should be fairly rare that a Composable wraps another one and exposes all its children, so that problem should be rare enough that it's not really an issue’?
👍 1
1
n

Nacho Ruiz Martin

07/26/2021, 6:52 AM
I don’t completely agree about it being that rare. When building a design system it’s quite normal to wrap up (it was inheritance before) a base Composable exposing everything but adding some logic and even extra parameters. Maybe you won’t expose all its parameters, but a good amount of them.
c

CLOVIS

07/26/2021, 9:18 AM
If you don't expose all of them, though, then the solution that copies all of them (eg via a plugin) is not useful to you.
👌 1
I think the best way is just to copy all you need, and have global/companion default values (so you don't have magical default values everywhere)
n

Nacho Ruiz Martin

07/26/2021, 9:31 AM
Sounds like the most straightforward solution, yes. Thanks, man!
6 Views