Is there a way to check if a `lateinit var func: (...
# announcements
r
Is there a way to check if a
lateinit var func: () -> Unit
has been initialized? Or, if there’s a better strategy for this, I’m open to other solutions.
a
::func.isInitialized
s
Still, use
isInitialized
with caution. I’d use either a nullable var:
var func: (() -> Unit)? = null
or a lazy one, where it will be initialized lazily given the class’ dependencies:
val func: () -> Unit by lazy { /* create value for func */ }
(if you have set-up your dependencies (of the class that contains the
val func
) correctly, using
by lazy
should work fine)
r
There are a list of lambdas that can be optionally defined, and based on whether they’re supplied by a consumer, it will change the resulting object’s functionality. This makes
by lazy
not an option. But I think the nullable field is probably a better route.
1
d
Sounds right.
lateinit
is not designed for things that may not be set, it's definitely for values that you know will have a value the first time you access them.
s
I reserve
lateinit
only for classes whose lifecycle is not under your control and are initialized on a callback later (eg onCreate(...), initialize(...) calls, dependency @Inject, etc).
💯 4