What is the purpose of leading underscores in variable names in Kotlin?

Viewed 1409

I am new in Kotlin and confused in underscore in a variable as _view.
Please help me.

class MainActivityPresenter(_view: View): Presenter {
    
        private var view: View = _view
1 Answers

Maybe you can read about Names for backing properties and you'll understand it better.

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

This is common in viewModel where you have your private val of a MutableLiveData and then you have the same name variable without the underscore that is the one is accessible from outside but not mutable.

Example :

private val _user: MutableLiveData<User>
val user: LiveData<User>
    get() = _user

In your case would be to don't confuse the View that is in your Presenter and the View that is by constructor.

Related