androidkotlinencapsulationandroid-viewmodelbacking-field

Android : Translate in Java the Kotlin ViewModel backing field encapsulation technique


In an Android App written in Kotlin, LiveData properties in the ViewMoel can be encapsulated using the backing field technique like so :

private val _score = MutableLiveData<Int>()
val score: LiveData<Int>
    get() = _score

How can I translate this in Java to obtain the same level of encapsulation ?


Solution

  • In Java, class only have field and function, so you can create a private field with a getter like this to achieve the result.

    private final MutableLiveData<Int> score = new MutableLiveData<>();
    
    public final LiveData<Int> getScore(){
        return score;
    }