3

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

3 Answers3

4

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.

Yoni Gibbs
  • 6,518
  • 2
  • 24
  • 37
  • 1
    Better use `by lazy` instead of `= lazy` (https://kotlinlang.org/docs/reference/delegated-properties.html#lazy). – Alexey Romanov Nov 29 '18 at 11:36
  • Agreed, thanks @AlexeyRomanov. Have updated my answer accordingly. – Yoni Gibbs Nov 29 '18 at 12:02
  • What if there is no default constructor available? – IgorGanapolsky Jun 03 '20 at 18:38
  • You don't need to use a default constructor. The code in the lambda you pass to `lazy` can access whatever variables are in scope, so can use those to construct an object that needs parameters. (Obviously those variables need to be initialised themselves too.) – Yoni Gibbs Jun 04 '20 at 06:02
0
object GameDao {
    fun hereGoesYourFunctions()
}

calling hereGoesYourFunctions will initialize the GameDao class.

Zun
  • 1,553
  • 3
  • 15
  • 26
-1

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
    }
}
Vikash Bijarniya
  • 404
  • 4
  • 10