'Is it possible to pass Android Composables as an array?

In the example below I can pass several composables as a function to a Column. Is it possible to pass them in any other way? Ideally, as an array of composables.

class ComponentScreen : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MyApplicationTheme {
            // A surface container using the 'background' color from the theme
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {
                Column(content = function())
            }
        }
    }
}

@Composable
private fun function(): @Composable() (ColumnScope.() -> Unit) {
    return {
        Greeting("Android")
        Greeting("Android2")
    }
}
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

For instance, could I pass something like... ?

@Composable
private fun function(): @Composable() (ColumnScope.() -> Unit) = arrayListOf(Greeting("Android"), Greeting("Android2"))

(In this format it won't compile as it isn't ColumnScope.() -> Unit)



Solution 1:[1]

Return type of Greeting("Android") is Unit, so you can't put it in an array like this.

You can create an array of composables like this:

private fun function(): List<@Composable (ColumnScope.() -> Unit)> =
    listOf(
        { Greeting("Android") },
        { Greeting("Android2") }
    )

Note that this function doesn't need to be Composable.

You can't simply pass result of this function into Column, but here's how you can unfold it:

Column {
    function().forEach { view ->
        view()
    }
}

If you plan to use it intensively, you can create a wrapper for such case:

@Composable
fun Column(
    modifier: Modifier = Modifier,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    views: List<@Composable (ColumnScope.() -> Unit)>,
) {
    Column(
        modifier = modifier,
        verticalArrangement = verticalArrangement,
        horizontalAlignment = horizontalAlignment,
    ) {
        views.forEach { view ->
            view()
        }
    }
}

Then you easily use it as following:

Column(views = function())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pylyp Dukhov