How to write a static packet level initializer in Kotlin?

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.

+5
source share
3 answers

There is currently no way to add code to the static constructor generated for the Kotlin file classes, only top-level property initializers get there. It sounds like a function request, so now there is a problem to keep track of this: KT-13486 packet-level init blocks

Another workaround is to place the initialization in a private / internal top-level object and reference this object in those functions that depend on the effect of this initialization. Objects are initialized lazily when they are referenced for the first time.

 fun dependsOnState(arg: Int) = State.run { arg + value } private object State { val value: Int init { value = 42 println("State was initialized") } } 
+4
source

As you already mentioned, you need a property with something that was launched during initialization:

 val x = run { println("The package class has loaded") } 
+3
source

I circumvented it using the top-level Backing property under the Kotlin file. Kotlin Docs: Backup Properties

 private var _table: Map<String, Int>? = null public val table: Map<String, Int> get() { if (_table == null) { _table = HashMap() // Type parameters are inferred // .... some other initialising code here } return _table ?: throw AssertionError("Set to null by another thread") } 
0
source

All Articles