A previous question shows how to put a static initializer inside a class using its companion object
. I'm trying to find a way to add a static initializer at the package level, but it seems packages have no companion object.
// compiler error: Modifier 'companion' is not applicable inside 'file'
companion object { init { println("Loaded!") } }
fun main(args: Array<String>) { println("run!") }
I've tried other variations that might've made sense (init
on its own, static
), and I know as a workaround I can use a throwaway val
as in
val static_init = {
println("ugly workaround")
}()
but is there a clean, official way to achieve the same result?
Edit: As @mfulton26's answer mentions, there is no such thing as a package-level function really in the JVM. Behind the scenes, the kotlin compiler is wrapping any free functions, including main
in a class. I'm trying to add a static initializer to that class -- the class being generated by kotlin for the free functions declared in the file.