2

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
   }
1
  • 1
    Could you please elaborate on your use case? Also, what is createLazyObject() here? Last but not least, is this initialization intended to change the state of the object itself or the containing class? Commented Feb 1, 2022 at 12:09

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Here in also our context is Lazy<T> instead of T. So, I can't get access to created object.
ok, find my error. It's on incorrect question. Sorry. Your answer here is correct.
1

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
*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.