Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton with isInitialized check

Tags:

android

kotlin

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

like image 220
Ivan Carrasco Alonso Avatar asked Jun 28 '26 06:06

Ivan Carrasco Alonso


1 Answers

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.

like image 116
Yoni Gibbs Avatar answered Jul 01 '26 03:07

Yoni Gibbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!