Is it possible to have a function invoked when an ...
# getting-started
a
Is it possible to have a function invoked when an instance of a specific class is created in a class? Such as:
Copy code
class SomeClass {
    val listOfThing = Array<Thing>()
    val thing1 = Thing()

    fun Thing.invoke() {
        listOfThing.add(this)
    }
}
r
Assuming I'm understanding you right, no, you cannot intercept the initialization of a class. You could just create a helper function though.
Copy code
class SomeClass {
    val listOfThing = Array<Thing>()
    val thing1 = makeThing()

    fun makeThing(): Thing = Thing().also(listOfThing::add)
}
p
if you really wanted your code to look like it's still calling the constructor (I'd not recommend it as it can obscure the side effect) you can use a lambda in a badly named variable. Something like this:
Copy code
class SomeClass {
    val listOfThing = mutableListOf<Thing>()
    private val Thing = { Thing().also { listOfThing += it } }
    
    val thing1 = Thing()
}