1

I'm a beginner to Android development.

When making a singleton in the Application Context, here is my code.

I pass the application context to the instantiation

class Blah{
 companion object {
        @Volatile
        private var INSTANCE: Blah? = null

        //Singleton
        fun getInstance(applicationContext: Context): Blah =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: Blah(applicationContext).also { INSTANCE = it }
            }
     }
}

Can I pass the application directly to the instantiation? Like so:

class Blah{
 companion object {
        @Volatile
        private var INSTANCE: Blah? = null

        //Singleton
        fun getInstance(application: Application): Blah =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: Blah(application).also { INSTANCE = it }
            }
     }
}

Will this present memory leaks?

1 Answer 1

1

Application is also a singleton. This doesn't cause a memory leak because there is only one instance of Application and when your app is running you have one and when your app isn't running there is nothing there, so go for it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.