Why is `by` used instead of assignment at ```var i...
# compose
a
Why is
by
used instead of assignment at
Copy code
var isSelected by remember { mutableStateOf(false) }
I’m following Google’s codelab
m
I am just a beginner, so take my response with a grain of salt.
mutableStateOf(T)
returns a
MutableState<T>
object where the value is stored in
MutableState<T>.value
So, if you don't want to use
by
, your code would look like this:
Copy code
val isSelected = remember { mutableStateOf(false) }
To retrieve state, you need
isSelected.value
And to change state, you would do this:
Copy code
isSelected.value = true
Using
by
you can tell Kotlin to use the getter and setter function of the state (you need some extra imports for this functionality) whenever you get or set the value of the variable
isSelected
Those getter and setters would modify the
value
parameter of the state object under the hood. In other words, instead of
isSelected.value
you can just use
isSelected
To change
isSelected
, instead of the previous code, you can simply write
Copy code
isSelected = true
Tldr: Using
by
keyword, you can simply treat the mutable state object as a normal variable.
1