Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initialisation block in Kotlin

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.

like image 344
Marcin Koziński Avatar asked May 16 '16 20:05

Marcin Koziński


People also ask

What is static initialisation block?

A Static Initialization Block in Java is a block that runs before the main( ) method in Java. Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.

What is initializer block in Kotlin?

Kotlin initThe code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated, with any kind of constructor as we shall see next. Multiple initializer blocks can be written in a class.

What is need of static and initializer block?

Java 8Object Oriented ProgrammingProgramming. Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.


2 Answers

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

like image 118
hotkey Avatar answered Oct 04 '22 16:10

hotkey


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

like image 25
abhilasha Yadav Avatar answered Oct 04 '22 15:10

abhilasha Yadav