Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I store a composable function in a variable?

In Kotlin, function is a first-class citizen. We can store a function in a variable as below

val functionVariable: () -> Unit = ::myFunction

fun myFunction() { }

However, for @Composable function, how can I do so?

If I did the below, it will cry foul i.e. org.jetbrains.kotlin.diagnostics.SimpleDiagnostic@e93b05f8 (error: could not render message)

val functionVariable: () -> Unit = ::myFunction

@Composable
fun myFunction() { }

Is there a way to store composable function as a variable?

like image 429
Elye Avatar asked Mar 27 '21 08:03

Elye


1 Answers

Composable function reference is not yet supported (and that's what the error message actually is). Besides, @Composable annotation is part of the function signature because it adds some parameters to the function. So you need to use val functionVariable: @Composable () -> Unit = { myFunction() }.

like image 131
H.D. Avatar answered Sep 28 '22 11:09

H.D.