I was looking to use mutable state to declare a va...
# compose
r
I was looking to use mutable state to declare a variable without initializing it and with the benefit of delegate syntax. If I do
lateinit var myState: MutableState<MyState>
then I have to reference with
myState.value.myProperty
. If I do
var myState: MyState? by mutableStateOf(null)
then I have to reference with
myState?.myProperty
(or other ways of dealing with nullable types). Is there a form that lets you use
myState.myProperty
with
lateinit
?
a
Copy code
private var _myState by mutableStateOf<MyState?>(null)
var myState: MyState
  get() = _myState ?: error("myState was not initialized")
  set(value) {
    _myState = value
  }
and hopefully you aren't using
lateinit
often enough for the above to be cumbersome at scale 🙃
if you are, (a) probably try to avoid that much
lateinit
, (b) you could write your own implementation of the
MutableState<T>
interface and a
lateinitMutableStateOf
factory function of your own that does the above for you and reuse the existing property delegate functions
r
Very cool, thanks. I don't have too many `lateinit`s -- just trying to avoid a "dummy" initialization for an object or two that don't get their real initial state until preferences are read.