Ii) Allowed with only non-nullable data types lateinit var name: String //Allowed ![]() I) Use it with mutable variable lateinit var name: String //Allowed This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.Īlso, there's another way not mentioned in the question: Delegates.notNull(), which is suitable for deferred initialization of non-null properties, including those of Java primitive types. It will then store the references and release them only once the property has been initialized. Val myLazyString: String by lazy may capture references from the context where it is used into its closure. Lazy() is a function that takes a lambda and returns an instance of Lazy which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result. In Kotlin, if you don't want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language reference):
0 Comments
Leave a Reply. |