Kotlin Lateinit Properties With Custom Setter

Mar 4, 2020
Non-nullable Backed Properties

I have a properties with custom getter and setter.

  • The properties is backed by a field/variable for performance reason
  • The properties is non-nullable because I am sure it has value

Sadly lateinit cannot be applied on properties with custom getter and setter, so alternative solution is for the properties to be backed by another variable.

class HomeViewModel(private val state: SavedStateHandle) : ViewModel() {    companion object {        private const val STATE_UPLOAD_PHOTO = "uploadPhoto"    }    @Parcelize    class UploadPhotoState(var isActive: Boolean = false, var totalCount: Int = 0): Parcelize    private var _uploadPhotoState: UploadPhotoState? = null    var uploadPhotoState: UploadPhotoState        get() {            return _uploadPhotoState ?: run {                val newValue = state.get<UploadPhotoState>(STATE_UPLOAD_PHOTO) ?: UploadPhotoState()                _uploadPhotoState = newValue                return newValue            }        }        set(value) {            _uploadPhotoState = value            state.set(STATE_UPLOAD_PHOTO, value)        }}

Solution for Nullable Properties

var uploadPhotoState: UploadPhotoState? = null    get() {        return field ?: run {            val newValue = state.get<UploadPhotoState>(STATE_UPLOAD_PHOTO) ?: UploadPhotoState()            field = newValue            return newValue        }    }    set(value) {        field = value        state.set(STATE_UPLOAD_PHOTO, value)    }

NOTE: Another solution is to initialized uploadPhotoState with an instance (instead of null) which contain an internal flag to indicate this instance is actually new / null.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.