I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters. There is another singleton that takes a constructor parameter.

Java code:

public class TasksLocalDataSource implements TasksDataSource {

    private static TasksLocalDataSource INSTANCE;

    private TasksDbHelper mDbHelper;

    // Prevent direct instantiation.
    private TasksLocalDataSource(@NonNull Context context) {
        checkNotNull(context);
        mDbHelper = new TasksDbHelper(context);
    }

    public static TasksLocalDataSource getInstance(@NonNull Context context) {
        if (INSTANCE == null) {
            INSTANCE = new TasksLocalDataSource(context);
        }
        return INSTANCE;
    }
}

My solution in kotlin:

class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {

    private val mDbHelper: TasksDbHelper

    init {
        checkNotNull(context)
        mDbHelper = TasksDbHelper(context)
    }

    companion object {
        lateinit var INSTANCE: TasksLocalDataSource
        private val initialized = AtomicBoolean()

        fun getInstance(context: Context) : TasksLocalDataSource {
            if(initialized.getAndSet(true)) {
                INSTANCE = TasksLocalDataSource(context)
            }
            return INSTANCE
        }
    }
}

Am I missing anything? Thread safety? Laziness ?

There were a few similar questions but I don't like the answers :)

  • It's a bit awkward that the INSTANCE property exposes public setter – miensol Nov 3 '16 at 9:47
  • @miensol any other option to pass the parameter (Context) to the companion object? – LordRaydenMK Nov 3 '16 at 9:48
  • 1
    Storing a Context instance in a global singleton object (no matter whether Java or Kotlin) creates a memory leak: stackoverflow.com/a/11908685/147024 – yole Nov 3 '16 at 9:59
  • 3
    @yole it is NOT a memory leak if it is the application context which is a singleton. – LordRaydenMK Nov 3 '16 at 10:00
  • 1
    @LordRaydenMK I think there are 4 improvements in your code if you use Kotlin in Android. I have made a gist with some explaination. Check it out : gist.github.com/gaplo917/f186d5c541fbc0d6f77f9b720ec4694c – Gary LO Nov 4 '16 at 3:52
up vote 41 down vote accepted

Here's a neat alternative from Google's architecture components sample code, which uses the also function:

class UsersDatabase : RoomDatabase() {

    companion object {

        @Volatile private var INSTANCE: UsersDatabase? = null

        fun getInstance(context: Context): UsersDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(context.applicationContext,
                    UsersDatabase::class.java, "Sample.db")
                    .build()
    }
}
  • I am not sure why there is INSTANCE ?: inside synchronized block? Because that block will be called only when INSTANCE was null so why to check INSTANCE was null or not again there? Can someone explain? – Sandip Soni Jun 18 at 6:51
  • 2
    @SandipSoni Read about double-check locking: stackoverflow.com/questions/18093735/… – kuhnroyal Jun 23 at 11:53

I am not entirely sure why would you need such code, but here is my best shot at it:

class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {
    private val mDbHelper = TasksDbHelper(context)

    companion object {
        private var instance : TasksLocalDataSource? = null

        fun  getInstance(context: Context): TasksLocalDataSource {
            if (instance == null)  // NOT thread safe!
                instance = TasksLocalDataSource(context)

            return instance!!
        }
    }
}

This is similar to what you wrote, and has the same API.

A few notes:

  • Do not use lateinit here. It has a different purpose, and a nullable variable is ideal here.

  • What does checkNotNull(context) do? context is never null here, this is guarantied by Kotlin. All checks and asserts are already implemented by the compiler.

UPDATE:

If all you need is a lazily initialised instance of class TasksLocalDataSource, then just use a bunch of lazy properties (inside an object or on the package level):

val context = ....

val dataSource by lazy {
    TasksLocalDataSource(context)
}
  • Exactly what I was looking for... About the usage of this code... I am trying to convert github.com/googlesamples/android-architecture to Kotlin to get my feet wet with Kotlin and to compare the code. That is why I don't want to include Dagger or github.com/SalomonBrys/Kodein – LordRaydenMK Nov 5 '16 at 14:22
  • Out of curiosity, what file was you trying to convert? – voddan Nov 5 '16 at 14:27
  • 1
    @LordRaydenMK IMHO, don't start learning Kotlin by doing a Java conversion. Read the official documentation once, try to do a complete equivalent Kotlin implementation starting from scratch but not doing a Java conversion. Concept of "Don't code Kotlin in Java way" is very important because most of the time you don't need Java (in)famous coding pattern (as it was designed for Java). – Gary LO Nov 5 '16 at 18:12
  • 1
    @GaryLO I did the koans on try.kotlinglang.org. As Hadi Hariri (twitter.com/hhariri) said in a talk on some conference (can't find the link now)... some Kotlin is better than no Kotlin for start. And the reason I wrote here is to try and do it the Kotlin way. Thanks. – LordRaydenMK Nov 5 '16 at 18:21
  • 1
    Beware that this solution is not thread-safe. Two singleton instances may exist and get initialized if multiple threads try to access it simultaneously. – BladeCoder Jul 23 '17 at 18:14

You can declare a Kotlin object, overloading "invoke" operator.

object TasksLocalDataSource: TasksDataSource {
    private lateinit var mDbHelper: TasksDbHelper

    operator fun invoke(context: Context): TasksLocalDataSource {
        this.mDbHelper = TasksDbHelper(context)
        return this
    }
}

Anyway I think that you should inject TasksDbHelper to TasksLocalDataSource instead of inject Context

if you want to pass a parameter to the singleton in an easier way I think this is better and shorter

object SingletonConfig {

private var retrofit: Retrofit? = null
private const val URL_BASE = "https://jsonplaceholder.typicode.com/"

fun Service(context: Context): Retrofit? {
    if (retrofit == null) {
        retrofit = Retrofit.Builder().baseUrl(URL_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
    }
    return retrofit
}

}

and you call it in this easy way

val api = SingletonConfig.Service(this)?.create(Api::class.java)

If the only parameter you need is the application Context, then you can initialize it to a top level val, early in a ContentProvider, like the Firebase SDK does.

Since declaring a ContentProvider is a bit cumbersome, I made a library that provides a top level property named appCtx for all places where you don't need an Activity or other special lifecycle bound context.

Singletons

Singletons are used often enough for a simpler way of creating them to exist. Instead of the usual static instance, getInstance() method and a private constructor, Kotlin uses the object notation. For consistency, object notation is also used to define static methods.

 object CommonApiConfig {
private var commonApiConfig: CommonApiConfig? = null
fun getInstance(): CommonApiConfig {
    if (null == commonApiConfig) {
        commonApiConfig = CommonApiConfig
       }
    return CommonApiConfig.commonApiConfig!!
   }
}
  • 1
    Does NOT answer the question. The question is how to create a singleton when you have to pass an argument in the constructor. – LordRaydenMK Oct 5 '17 at 16:42

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.