Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notified when lateinit var has been initialised (Kotlin)

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

like image 884
SARose Avatar asked Dec 07 '17 01:12

SARose


People also ask

How do you check if a Lateinit variable has been initialized Kotlin?

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.

How do you check if Lateinit VAR is initialized or not?

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.

What happens when a field declared as Lateinit is accessed before it is initialized?

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.

How do you initialize Lateinit object in Kotlin?

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".


1 Answers

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")
}
like image 113
voddan Avatar answered Jan 03 '23 15:01

voddan