Is there a way to check if a `lateinit var func: (...
# announcements
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.
Still, use
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)
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.
Sounds right.
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.
I reserve
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