https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Anthony Flores

04/24/2022, 5:19 PM
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

Ruckus

04/24/2022, 5:24 PM
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

phldavies

04/24/2022, 7:32 PM
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()
}
2 Views