1

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 ?

4
  • 2
    but i didn't see that properly encapsulates the showDialog var well, how come? The approaches are basically equivalent. The second option is just defining a second useless variable. Commented Jan 2, 2023 at 14:46
  • Agree with @marstran, there's no cons here so you should prefer readability. Commented Jan 2, 2023 at 14:59
  • this code is in a viewmodel class ,with the first approach ,the exposed property is mutable var and can be altered, the second approach, the exposed property is immutable val and we can't redefine it from outside the class. Commented Jan 2, 2023 at 15:36
  • @joghm In the first approach, the setter is private. So it cannot be altered from outside the class. In the second approach, the _showDialog is still mutable, so if it changes the val will still change value because it re-fetches it every time get is called. A val is not immutable, it is just read-only. Commented Jan 2, 2023 at 16:06

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ,that was helpful,i will add this i'm using this to keep the state after process death @OptIn(SavedStateHandleSaveableApi::class) var showDialog by savedStateHandle.saveable { mutableStateOf(false) } private set
1

By defining set as a private method, only members of the current class can assign data to the variable and get method can be accessed as-usual.

class A { // readable by everyone // writable by only members of the current class var a = "a" private set // readable & writable by only members of the current class private var b = "b" // readable & writable by everyone var c = "c" } 

I prefer using the first one as it is concise and more readable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.