Not able to import getInstance in a class

Viewed 12

I have created a class My Singleton and tried to call getInstance, but it won't import it.Below is the My singleton class which I have created- [Image Link- https://postimg.cc/471L7sr0]

package com.example.memeshare
import android.content.Context
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.Volley

 class MySingleton {
     class MySingleton constructor(context: Context) {
         companion object {
             @Volatile
             private var INSTANCE: MySingleton? = null
             fun getInstance(context: Context) =
                 INSTANCE ?: synchronized(this) {
                     INSTANCE ?: MySingleton(context).also {
                         INSTANCE = it
                     }
                 }
         }
         private val requestQueue: RequestQueue by lazy {
             // applicationContext is key, it keeps you from leaking the
             // Activity or BroadcastReceiver if someone passes one in.
             Volley.newRequestQueue(context.applicationContext)
         }
         fun <T> addToRequestQueue(req: Request<T>) {
             requestQueue.add(req)
         }
     }
 }
`
1 Answers

The problem is being caused by nesting class. MySingleton class is nested or wrapped inside the same class i.e. MySingleton as shown below.

//1st class
class MySingleton {

//2nd nested class
class MySingleton constructor(context: Context) {
         companion object {

Solution is to use MySingleton.MySingleton.getInstance() to access the second class but is approach is awful.

I don't see the need for wrapping the same class, therefore remove the first class and remain with the inner MySingleton class. That way you will be able to access the 2nd class companion object.

Related