I would like to know the difference between:
var textFieldState = remember {
mutableStateOf("")
}
and
var textFieldState by remember {
mutableStateOf("")
}
Is there any advantage over the other?
CodePudding user response:
Is there any advantage over the other?
The first really should be a val
and not a var
. Otherwise, they are equivalent. Or, to quote the documentation:
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.
In those three:
- In the first,
mutableState
holds aMutableState
, and you use.value
and.value=
to manipulate the contents - In the second,
value
holds aMutableState
, but theby
syntax tells the compiler to treat it as a property delegate, so we can pretend thatvalue
just holds the underlying data - In the third, a destructuring declaration gives you getter and setter references to manipulate the content in the underlying
MutableState
CodePudding user response:
The by
in this context is a kotlin property delegate. Any class that implements the operator fun operator fun getValue(thisRef: Any?, prop: KProperty<*>): T
can use this syntax. Using =
will eagerly assign the variable (importantly without delegation), the by
will delegate to the operator function. The remember
in this case is just a shortcut function to creating the Remember delgate that wraps the value you are creating inside the { ... }
block.
A typical example is the kotlin Lazy<T>
class : val myValue : Int by lazy { 1 }
. If used with the by
operator you will return the Int
value, if used with =
it will return Lazy<Int>
as you have not used delegation.
It is also worth noting that delgates can be setters as well by using this operator fun : operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: T)
.