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.