Do we have a way to do some action with a lazy initializing object right after creation?
For example, smth like this:
val lazyInitObject by createLazyObject()
.apply {
// do some action with just created lazyInitObject
}
Not sure what your createLazyObject() is here, but with the standard lazy delegate you have full control over the initialization lambda:
val lazyInitObject by lazy {
createTheValue().also {
// do something with it
}
}
So if you want to allow this kind of thing you might want to design your custom delegate differently so it accepts a lambda.
Note that if what you want to do is only about changing the state of the lazily created object and not the enclosing class, you may want to simply use an init { } block in the object's class itself.
also our context is Lazy<T> instead of T. So, I can't get access to created object.Using the build in object I can describe some of how Kotlin will allow you to do this, and will allow you to define this more specifically for your use case.
This can absolutely be accomplished with built in tools, if you need a more specific usage, the .also {} standard function will help you tack on functionality after any call
object MyObject {
fun myFunctions() {
println("I have done my work - MyObject")
}
init {
// Calls on first reference...
println("Hello world! - I am initialized - MyObject")
}
}
println("My app has started")
MyObject.myFunctions()
/*
This prints:
My app has started
Hello world! - I am initialized - MyObject
I have done my work - MyObject
*/
interface ILazy {
fun myFunction()
}
val myLazy: ILazy by lazy {
val myObject = object : ILazy {
override fun myFunction() {
println("myLazy has done its work")
}
init {
println("Object declarative is run instantly - MyLazy")
}
}
println("Post object declaration - Lazy")
myObject
}
myLazy.myFunction()
/*
This prints:
Object declarative is run instantly - MyLazy
Post object declaration - Lazy
myLazy has done its work
*/
createLazyObject()here? Last but not least, is this initialization intended to change the state of the object itself or the containing class?