Caleb B
12/24/2025, 8:20 PMephemient
12/24/2025, 8:51 PMephemient
12/24/2025, 8:52 PMYoussef Shoaib [MOD]
12/24/2025, 8:53 PMkotlin.run for that purpose)Daniel Pitts
12/26/2025, 6:14 PMclass MyClass(...) {
companion object {
operator fun invoke(...): MyClass {
// Do the complex stuff.
return MyClass(...)
}
}
}
This is also particularly useful if you need to use "suspend" calls, or use generic type arguments that aren't part of the class signature.Daniel Pitts
12/26/2025, 6:16 PMsuspend fun MyClass(stuff: Stuff) {
// do things with stuff.
return MyClass().
}
I personally prefer the companion object approach, but I don't have any good reason why 😉Caleb B
12/26/2025, 7:53 PMI personally prefer the companion object approach, but I don't have any good reason whyI prefer it too, and it's because the import is different from the class itself, and ctrl+clicking the symbol is guaranteed to link to the right symbol. Something I keep experiencing with the IR builders is having to manually find the
IrXImpl function in builders.kt because it keeps linking to the constructor by default. At least with .invoke the IDE can disambiguate them, plus it's inside the class itself instead of off somewhere else.