Adam Hurwitz
1 min readMar 30, 2019

I understand the need for creating getter and setter points for LiveData in the ViewModel. However, I am looking to understand how the get() syntax works in Kotlin.

ie:

val isRealtime: LiveData<Boolean>
get() = _isRealtime
private val _isRealtime = MutableLiveData<Boolean>()`

Here is a good explanation on Stackoverflow: How Does Android LiveData get() syntax work?

get() is not related to Android.

val isRealtime: LiveData<Boolean>
get() = _isRealtime

Here, get() is overriding the automatically-generated Kotlin getter function for the isRealtime property. So, instead of returning its own value, it returns the value of _isRealtime.
Personally, I recommend simpler syntax:

private val _isRealtime = MutableLiveData<Boolean>()
val isRealtime: LiveData<Boolean> = _isRealtime

The objective of either of these is to keep the mutability private, so consumers of this class do not accidentally update the MutableLiveData themselves.

Adam Hurwitz
Adam Hurwitz

Written by Adam Hurwitz

An account about nothing | Researcher and product consultant

No responses yet