Ivan Carrasco Alonso
Ivan Carrasco Alonso

Reputation: 103

Singleton with isInitialized check

I´m developing a singleton class in Kotlin but I want check if the lateinit var "instance" is Initialized instead check if is null but It doesnt work. I think is better init the var like lateinit and no like null var.

companion object {
    private lateinit var instance: GameDAO

    fun getInstance(): GameDAO {
        if (!::instance.isInitialized) {
            synchronized(this) {
                instance = GameDAO()
            }
        }
        return instance
    }
}

The compiler show me the next error: enter image description here

Upvotes: 3

Views: 1246

Answers (3)

Yoni Gibbs
Yoni Gibbs

Reputation: 7018

I think what you're trying to achieve can best be done using the lazy function to lazily initialise a value when first requested. See here for details.

e.g.

companion object {
    val instance: GameDAO by lazy { GameDAO() }
}

You don't need a separate getInstance function: you can just access the instance property directly, and it'll be initialised on first request (in a thread-safe way).

This is assuming that you only want the object to be initialised when first requested (i.e. lazily initialised). If you want it to always be created then you can just construct it and assign it to a variable/property immediately.

Upvotes: 4

Vikash Bijarniya
Vikash Bijarniya

Reputation: 424

You may try even better approach :

class SingletonClass private constructor() {

init {
    println("This ($this) is a singleton")
}

private object Holder {
    val INSTANCE = SingletonClass()
}

companion object {
    val instance: SingletonClass by lazy {
        Holder.INSTANCE
    }
}

Upvotes: -1

Zun
Zun

Reputation: 1681

object GameDao {
    fun hereGoesYourFunctions()
}

calling hereGoesYourFunctions will initialize the GameDao class.

Upvotes: 0

Related Questions