https://kotlinlang.org logo
#android
Title
# android
a

arekolek

12/16/2017, 11:08 PM
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

stantronic

12/17/2017, 1:09 PM
k

kingsley

12/18/2017, 3:24 PM
No. He’s trying to hide the fact that the
data
is mutable, and rather expose it as a simple
LiveData
s

stantronic

12/20/2017, 10:26 AM
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

kingsley

12/20/2017, 10:47 AM
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

stantronic

12/20/2017, 4:51 PM
Ok. Good to know 🙂 In which case I don’t see the advantage of removing the backing property
k

kingsley

12/21/2017, 6:55 PM
Exactly. There’s always a backing property anyway. It’s just sometimes more verbose 🙂
a

arekolek

01/02/2018, 10:32 AM
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