Is it possible to achieve encapsulation of the con...
# android
a
Is it possible to achieve encapsulation of the concrete type:
Copy code
public class DataViewModel {
    private MutableLiveData<String> data = new MutableLiveData<>();

    public LiveData<String> getData() {
        return data;
    }
}
in Kotlin without resorting to having a backing property?
Copy code
class DataViewModel {
    private val _data = MutableLiveData<String>()

    val data: LiveData<String> get() = _data
}
s
k
No. He’s trying to hide the fact that the
data
is mutable, and rather expose it as a simple
LiveData
s
yes, but you could do that by making the private val a Jvm field, which would mean no getters and setters, and would be equivalent to the java code.
k
A
private val
as shown by Arek above already omits getters/setters, so there’s no need of a
@JvmField
. In fact, you cannot combine
@JvmField
and
private val
in the same declaration
s
Ok. Good to know 🙂 In which case I don’t see the advantage of removing the backing property
k
Exactly. There’s always a backing property anyway. It’s just sometimes more verbose 🙂
a
Either I missed that (https://kotlinlang.org/docs/reference/properties.html#backing-properties), or it was added to the documentation recently, so thanks for mentioning that!
👍 1