What's difference between "= remember" and " by remember" (Kotlin, Jetpack Compose)

Viewed 4376

I think two use case of remember exist.
first one is

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

and second

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

Is there any functional differencies exist? or just for convenience?

3 Answers

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.

Cheers

i've noticed a slight difference between both expressions :

when using

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

var aa will be of type MutableState.

in case "by" is used

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

var aa will be considered of type Boolean. personally i prefer using by to preserve the primitive types.

in the first case: you have to use "aa.value" whenever you want to use the value of "aa". in the second case: you don't have to, because under the hood you aren't using the getter of the var.

additional:

  • you know that whenever you call or edit a variable you are under the hood calling its getter and setter functions, so when you use "by" you are using another getter and setter which delegated to another piece of code (usually to the function the comes after "by" keyword) and then you do not have to use "aa.value", you just can write "aa" when call it or "aa = true" when you set it.
  • "var" have setter and getter functions because it is editable, while "val" have just getter and no setter cause it is not editable (read only).

note: if you want to read more then check this answer for a well understanding of the concept: read more

Related