Zach Bublil
Zach Bublil

Reputation: 867

singleton - init not called

I want to create a singleton in Kotlin so I made a companion object like this:

companion object { 
    val INSTANCE = MessagesManager()
}

There is something I want to do in its constructor so I wrote some code in the init function but it never runs if I don't use the Singleton. I also tried to use the JVMField annotation but it doesn't work. I want the init run would run immediately after startup.

Upvotes: 1

Views: 1550

Answers (1)

Choim
Choim

Reputation: 392

init{} block will be called when the class is loaded.

So, you must access that class at least once after startup.

And, There is more comfortable way to make Singleton in Kotlin, like below.

object MessageManager {}

Upvotes: 2

Related Questions