Static initialisation block in Kotlin

Marcin Koziński picture Marcin Koziński · May 16, 2016 · Viewed 16.6k times · Source

What is the equivalent of a static initialisation block in Kotlin?

I understand that Kotlin is designed to not have static things. I am looking for something with equivalent semantics - code is run once when the class is first loaded.

My specific use case is that I want to enable the DayNight feature from Android AppCompat library and the instructions say to put some code in static initialisation block of Application class.

Answer

hotkey picture hotkey · May 16, 2016

From some point of view, companion objects in Kotlin are equivalent to static parts of Java classes. Particularly, they are initialized before class' first usage, and this lets you use their init blocks as a replacement for Java static initializers:

class C {
    companion object {
        init {
            //here goes static initializer code
        }
    }
}