This is a straight forward question but I cannot find an answer. Is there a way to be notified when a lateinit var
has been initialised in Kotlin?
I know I can check if it has been initialised with this::coolvar.isInitialized
but this is not the same.
Thank you
Along with this modifier, Kotlin provides a couple of methods to check whether this variable is initialized or not. Use "lateInit" with a mutable variable. That means, we need use "var" keyword with "lateInit". "lateInit" is only allowed with non-NULLable data types.
You can check if the lateinit variable has been initialized or not before using it with the help of isInitialized() method. This method will return true if the lateinit property has been initialized otherwise it will return false.
Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.
In order to create a "lateInit" variable, we just need to add the keyword "lateInit" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use "lateInit" in Kotlin. Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".
lateinit var
works well only in the simplest cases when uninitialized value doesn't make sense in the context of the app, such as dependency injection or late initialization in onCreate()
.
What you need is a property delegate with a particular behavior. Take a look at Delegates.observable
:
var coolvar by Delegates.observable("initial value") { _, old, new ->
println("coolvar has been updated")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With