99

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.

Marcin Koziński
  • 10,835
  • 3
  • 47
  • 61
  • checkout this [init-blocks kotlin vs Java](https://chetangupta.net/init-blocks/) I explained what is init block and how its invoked order plus how it's different from Java's init block, static init blocks etc – Chetan Gupta Jan 26 '21 at 06:21

2 Answers2

141

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
        }
    }
}

@voddan it's not an overkill, actually this is what suggested on the site of Kotlin: "A companion object is initialized when the corresponding class is loaded (resolved), matching the semantics of a Java static initializer." Semantic difference between object expressions and declarations

grabz
  • 69
  • 6
hotkey
  • 140,743
  • 39
  • 371
  • 326
  • 1
    companion object is an overkill here – voddan May 17 '16 at 05:13
  • 5
    @voddan, OP asked about executing code before the first usage of an existing class. Solution with `object` declaration requires one to actually use it somewhere because of lazy initialization. – hotkey May 17 '16 at 08:23
  • 2
    @voddan Would you care to explain why it's an overkill and what would are the alternatives? – Marcin Koziński Jul 10 '16 at 22:54
  • 2
    Sorry, my bad, I was mistaken to think you didn't cared about the class loading. The companion object is the right solution here – voddan Jul 11 '16 at 12:29
  • If static initialization is all you want to achieve, then the companion object should probably be made private or protected. – mipa Jan 01 '21 at 11:49
3
companion object  { 
    // Example for a static variable
    internal var REQUEST_CODE: Int? = 500

    // Example for a static method
    fun callToCheck(value: String): String {
        // your code
    }
}

An object declaration inside a class can be marked with the companion keyword.And under this we can use like java static method and variable.LIke classname.methodname or classname.variablename

rekire
  • 47,260
  • 30
  • 167
  • 264
abhilasha Yadav
  • 217
  • 1
  • 9