You are currently viewing kotlin Static Blocks

kotlin Static Blocks

In Kotlin, there is no direct equivalent to a static block like in Java. However, we can achieve similar behavior using a companion object with an init block. The code inside this init block will be executed when the class is loaded for the first time, similar to a static block in Java.

It is used to perform static initialization

class MyClass {
    companion object {
        init {
            // Code inside this block will be executed when the class is loaded.
            println("Static initialization")
        }
    }
}

We can think of the companion object as a container for static members in Kotlin. The init block inside it serves a similar purpose to static initialization in Java.

The code inside the init block will be executed the first time the class is accessed. If you want to ensure some initialization code is executed before any instances of the class are created, you can place it directly in the body of the class.

class Person(val firstName: String, val lastName: String) {
    val fullName: String


    // this block it will run every time new instance created
    init {
        fullName = "$firstName $lastName"
        println(fullName)
    }
     companion object {
        init {
            // Code inside this block will be executed when the class is loaded.
            // only run first time when class accessed
            println("Static initialization  ")
        }
    }
}

fun main() {
    val person1 = Person("justin", "bieber")
    val person2 = Person("Rohit", "Sharma")
}

you will see following output when you run the program

/**Output
 Static initialization  
justin bieber
Rohit Sharma
 * */

In this example, when person1 object is created static block will only run first time when class accessed, when person2 object created static block will not run again.

Here are some use cases where this approach can be beneficial:

  1. Initialization Logic: You can use the init block with in companion object to perform complex initialization logic that should be executed when the class is loaded.
  2. One-time Setup: If you need to set up resources or perform some one-time setup when the class is accessed, the init block in the companion object provides a suitable place to do so.
  3. Constants or Configuration: If you have constants or configuration values associated with the class, the companion object can hold them and be initialized accordingly.
Read : Want to know more about Kotlin Companion object? Explore Kotlin Companion Object

Also Read :