Search code examples
androidkotlinandroid-jetpack-compose

What's difference between "= remember" and "by remember"?


I see that are two ways to declare a variable with the remember API.

The first one is:

@Composable
fun abc() {
    var aa = remember { mutableStateOf(true) }
}

The second is:

@Composable
fun abc() {
    var aa by remember { mutableStateOf(true) }
}

Is there any functional difference between the two? Or are they just for convenience?


Solution

  • It is just for convenience, to shortify syntax. By using delegate (by keyword) you can skip relating to value because it is done under the hood.

    In the documentation you can read

    There are three ways to declare a MutableState object in a composable:

    val mutableState = remember { mutableStateOf(default) }
    var value by remember { mutableStateOf(default) }
    val (value, setValue) = remember { mutableStateOf(default) }

    These declarations are equivalent, and are provided as syntax sugar for different uses of state. You should pick the one that produces the easiest-to-read code in the composable you're writing.

    If default is of type Int:

    val mutableState : MutableState<Int> = remember { mutableStateOf<Int>(default) }
    var value : Int by remember { mutableStateOf<Int>(default) }
    val (value, setValue) = remember { mutableStateOf(default) }
    

    Cheers