Reputation: 909
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?
Upvotes: 62
Views: 23523
Reputation: 794
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
Upvotes: 58
Reputation: 808
One functional difference between them is that if you use by and then try to pass aa into another function where it is edited, that will not work. In that case aa will be a Boolean passed as val, which is not editable. If you use = and pass in MutableState<Boolean> then you can assign to aa.value inside your second function.
Upvotes: 4
Reputation: 661
I've noticed a slight difference between the two expressions.
In case =
is used
@Composable
fun abc() {
var aa = remember { mutableStateOf(true) }
}
then var aa
will be of type MutableState<Boolean>
.
In case by
is used
@Composable
fun abc() {
var aa by remember { mutableStateOf(true) }
}
then var aa
will be of type Boolean
.
Personally, I prefer using by
to preserve the primitive types.
Upvotes: 56
Reputation: 180
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:
note: if you want to read more then check this answer for a well understanding of the concept: read more
Upvotes: 10