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

312 Views Asked by At

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 ?

2

There are 2 best solutions below

3
On BEST ANSWER

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;
}
4
On

this is a normal getter method and this is the converted java code

private final MutableLiveData<Integer> _score = new MutableLiveData<Integer>();

@NotNull
public final LiveData<Integer> getScore() {
    return this._score;
}

this is the steps to get the java code form kotlin

in android studio

tools -> kotlin -> show kotlin byte code -> Decompile