Home > Software design >  How to declare Singleton instance in Kotlin , is it similar to how we declare Singleton class?
How to declare Singleton instance in Kotlin , is it similar to how we declare Singleton class?

Time:06-28

In an interview I was told to write a Singleton class so I wrote the following code

  object Ant{

    }

but later he asked me to write Singleton instance which confused me and I ended up writing like this

  object what{

   }

now, I know I am wrong but I am really curious how to write down Singleton Instance.

CodePudding user response:

please check my helper class, What I was using might be wrong so please correct me

class Helper{

    companion object{

    @Volatile
    var INSTANCE : Helper? = null

    fun getInstance(): Helper {
        return INSTANCE?: synchronized(this){
            val instance = Helper()
            INSTANCE = instance
            instance
        }
    }

  }

}

and then I would create a variable like this val helper = Helper.getInstance() and use this object from then on, sometimes I declare them as global variables outside class to make it easier to access across the app

recently we have shifted to Koin so we just declare these classes as singleton by using @Single ksp annotation

CodePudding user response:

It is hard to guess what an interviewer was asking about, after the event, but in your code above there is no instance of either Ant or What yet, only the object declaration. You would need to instantiate the object like:

val mySingleton = What

Object declarations are initialized lazily when first used

CodePudding user response:

I think you were right!

In Kotlin, an object is a singleton: it defines a class, with exactly one instance. (That one instance is created automatically, and you can't create any others.) So if you need a singleton, that's the standard way to get it.

You could do something like:

class Ant private constructor() {
    companion object {
        val INSTANCE = Ant()
    }
}

That's how you'd have to do it in Java: a private constructor and a single static instance. It may be that your interviewer was more familiar with Java, and was expecting you to do that — but that's absolutely pointless in Kotlin, because object does exactly the same, only more concisely (and with less opportunity for errors or race conditions or whatever).

If you were using a framework such as Spring, that provides other ways of creating single instances (e.g. with annotations such as @Component, @Bean, etc.) but those are specific to the framework, so you'd probably know if you needed anything like that.

Or your interviewer may have something else in mind — but in that case, he should have given you some hints; you're not a mind-reader!

The bottom line is that without any further information, object is the most obvious way to get a singleton, so from what you've posted, you were right.

  • Related