HelloCW
HelloCW

Reputation: 2335

Can I always use private set instead of private val in kotlin?

I read some kotlin project samples code, I find many author like to Code A.

I think Code B is more simpler.

1: Is Code B good way?

2: Can I always use private set intead of private val in Android Studio?

Code A

private val _uiState = MutableStateFlow(InterestsUiState(loading = true))
val uiState: StateFlow<InterestsUiState> = _uiState.asStateFlow()

Code B

var uiState = MutableStateFlow(InterestsUiState(loading = true))
    private set

Upvotes: 8

Views: 2001

Answers (2)

joghm
joghm

Reputation: 718

I have seen this example

var userName by mutableStateOf("")
   private set

but what i thought is best for a better encapsulation is this ,to deny the possibility of mutating the useName from outside the single source of truth (the viewmodel holder and responsible for managing the state )

  private var _userName by mutableStateOf("")
    val userName
        get() = _userName

Upvotes: 0

MJ Studio
MJ Studio

Reputation: 4631

A, B are not the same code.

In code A, define another variable as StateFlow is preventing to change value in StateFlow from out of class.

In code B, you can update value in StateFlow from out of class. Because you can refer MutableStateFlow.

Mutating state variable itself and Mutating state in StateFlow is different.

Observer observing StateFlow is received event when value in StateFlow is change but change StateFlow itself.

In other word, you should use code A for prevent to unexpected mutating from outer

Upvotes: 13

Related Questions