The previous question shows how to put a static initializer inside a class using the companion object . I am trying to find a way to add a static initializer at the package level, but the packages do not seem to have a companion object.
// compiler error: Modifier 'companion' is not applicable inside 'file' companion object { init { println("Loaded!") } } fun main(args: Array<String>) { println("run!") }
I tried other options that might make sense ( init yourself, static ), and I know how to work around this, I can use throwaway val , as in
val static_init = { println("ugly workaround") }()
but is there a clean, formal way to achieve the same result?
Edit: as the @ mfulton26 answer says , there is no such thing as a package level function in the JVM. Behind the scenes, the kotlin compiler wraps up any free functions, including main in the class . I am trying to add a static initializer to this class - a class created by kotlin for free functions declared in a file.
source share