4

I am new to Kotlin. Still learning basic syntax. I've heard about companion objects similar to static in Java. But don't know how to create synchronized singleton in Kotlin.

Borislav
  • 17
  • 9

4 Answers4

12

Just use

object Singleton {
    // any members you need
}

It's already synchronized properly:

Object declaration's initialization is thread-safe.

Note that this doesn't guarantee calls on it thread-safe, but that's just as in Java.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
2

There are also other ways, but those two are the most simple ones to generate a singleton class

Method 1- Kotlin Way

object SingletonObj {
    init {
        // do your initialization stuff
    }
}

Method 2- Double Null Check Way in Kotlin

class SingletonObj {
    private constructor(context: Context)

    companion object {
        @Volatile private var mInstance: SingletonObj? = null

        public  fun get(context: Context): SingletonObj =
            mInstance ?: synchronized(this) {
                val newInstance = mInstance ?: SingletonObj(context).also { mInstance = it }
                newInstance
            }
    }
}
hanilozmen
  • 460
  • 4
  • 8
2

Thread-safe and lazy:

class Singleton private constructor() {
    companion object {
        val instance: Singleton by lazy { Singleton() }
    }
}

Double null check already implemented inside by lazy.

Prilaga
  • 818
  • 10
  • 18
1

I think, little bit more research, and i found it . Here is how to do it . Please correct me if it can be done in better way.

companion object {
@Volatile private var INSTANCE: Singleton ? = null
 fun  getInstance(): Singleton {
         if(INSTANCE == null){
             synchronized(this) {
                 INSTANCE = Singleton()
             }
         }
         return INSTANCE!!
   }
}