Reputation: 5388
I have a function which takes in a Composable function as an argument
fun myFunction(content: @Composable () -> Unit) {
}
I want to control the different types of composables, a user can pass is as a parameter. More precisely, I only want the user to pass one of the following 3 functions as an argument.
@Composable
fun fun1() {}
@Composable
fun fun2() {}
@Composable
fun fun3() {}
How can I enforce this?
Upvotes: 0
Views: 91
Reputation: 471
A quick solution i can think of would be to use a functional interface in order for the content
parameter to be constrained by it.
So you would define a functional interface for you three functions :
fun interface ConstrainedContent {
@Composable
operator fun invoke()
}
Then you implement the interface for each of the content functions :
val function1 = object: ConstrainedContent {
@Composable
override fun invoke() {
Text("My Content 1")
}
}
Here I'm explicitly overriding the invoke method and not converting it as a lambda as there seems to be a type inference problem with the composable.
Then in your myFunction
@Composable
fun myFunction(content: ConstrainedContent) {
content()
}
So this would be a way to do it and only your implementations of the ConstrainedContent could be used in myFunction
but i'm not sure if there are some downside to this solution on the composition.
Upvotes: 2