Angel Koh
Angel Koh

Reputation: 13525

Error when using get() within @Composable (Jetpack Compose)

Is it possible to use the get() property within a @Composable function? I get an "unexpected token".

How do we use the set and get properties with compose?

val g:Int get()=88 // < works as expected outside @Composable

@Composable
fun Test() {
    val g:Int get()=88 // <  "unexpected token" error inside @Composable
}

enter image description here

Upvotes: 6

Views: 1833

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 88132

Backing properties are forbidden inside composeables because it stops Compose from updating when the get() results change and from caching the results for a repeated operation.

You should use remember variables. Learn more about states in compose.

Lets say your variable is computed depending on some other variables. Then, using remember, you can cache the result of that operation. You need to pass all the variables on which your g depends as keys to remember, so that it will only be computed once until one of the keys changes:

@Composable
fun TestView(a: Int = 44, b: Int = 2) {
    val g = remember(a, b) { a * b }
}

You can also use a view model, but in that case you will be responsible for the view being recomposed with the new g values, for example by using mutable states for values that will change. Also in this case the calculations will not be cached.

class ScreenViewModel : ViewModel() {
    val a by mutableStateOf(44)
    val b by mutableStateOf(2)
    val g: Int
        get() = a * b
}

@Composable
fun TestView() {
    val viewModel = viewModel<ScreenViewModel>()
    viewModel.g

Upvotes: 10

Related Questions