I have seen examples in the android official documentation that exposing property like that
var showDialog = mutableStateOf(false)
private set
but i didn't see that properly encapsulates the showDialog var well, so intended for this approach
private var _showDialog = mutableStateOf(false)
val showDialog
get() = _showDialog
which approach is much proper and better ?
CodePudding user response:
Both cases are equivalent here and both are probably wrong/not what you intended. In both cases, caller outside of the class will receive instance of MutableState<Boolean> which can be modified using state.value = x syntax.
What you've probably seen in documentation is this:
var showDialog by mutableStateOf(false)
private set
The only difference is by instead of =. With that, your showDialog property is plain Boolean backed by MutableState. You can still modify it inside the class, but you can't modify it outside of the class because of private set. Caller will get plain Boolean variable, doesn't have to know there is a MutableState behind it, and it is not able to modify it.
