joghm
joghm

Reputation: 717

Jetpack compose mutableState and encapsulation

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 ?

Upvotes: 1

Views: 976

Answers (2)

SURYA S R
SURYA S R

Reputation: 566

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.

Upvotes: 1

Jan Bína
Jan Bína

Reputation: 7218

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.

Upvotes: 4

Related Questions