I forget: does JVM bytecode (or the VM itself) man...
# compiler
c
I forget: does JVM bytecode (or the VM itself) mandate that `super()`/`this()` is the first call in a constructor? Or is that just a language thing? It would be nice to be able to run some preprocessing on the params before delegating to the primary ctor.
✅ 1
e
it's a language thing. in fact Java has relaxed it recently, https://openjdk.org/jeps/513
👀 1
similar feature request for Kotlin https://youtrack.jetbrains.com/issue/KT-81919
y
Btw, you can use secondary constructors and some utility functions to be able to do any arbitrary code you want. Effectively, the secondary constructor has a parameter for each variable you want, and the utility functions are used whenever you want to execute any statements (but you can also use
kotlin.run
for that purpose)
👍 1
d
Often times when I need to "do some stuff" before construction, I use the following pattern:
Copy code
class 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.
➕ 1
👍 1
The other pattern I've seen is just creating top level functions with the class name:
Copy code
suspend 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 😉
c
I personally prefer the companion object approach, but I don't have any good reason why
I 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.