【MVVM】 ViewModel の_プロパティ記述


Android Java ではあまり見かけなかったその記述。

Kotlin では、たくさん見かけてはいましたが、

private val _items = MutableLiveData<List<Task>>().apply { value = emptyList() }
val items: LiveData<List<Task>>
    get() = _items

private val _dataLoading = MutableLiveData<Boolean>()
val dataLoading: LiveData<Boolean>
    get() = _dataLoading

android-architecture/TasksViewModel.kt at todo-mvvm-live-kotlin · googlesamples/android-architecture

private val _repositories = MutableLiveData<List<Repo>>()
val repositories : LiveData<List<Repo>>
    get() = _repositories

android – Kotlin: Read Only access of Immutable Type to an Internal Variable of a Mutable Type – Stack Overflow

private val _models = ConflatedBroadcastChannel<Model>()
override val models: ReceiveChannel<Model> get() = _models.openSubscription()

private val _events = Channel<Event>(RENDEZVOUS)
override val events: SendChannel<Event> get() = _events

SdkSearch/SearchPresenter.kt at JakeWharton/SdkSearch


Names for backing properties
If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property:

class C {
  private val _elementList = mutableListOf<Element>()
  val elementList: List<Element>
      get() = _elementList

Properties and Fields: Getters, Setters, const, lateinit – Kotlin Programming Language

クラス内の処理実装に利用するのが _elementList で、
外部にただ公開するだけのが elementList。



👉【MVVM】ViewModel インスタンスの取得