Kotlin version of Java's getInstance()

So recently I’ve been using Android Architecture Components. In some example inside ViewModel we need to have a singleton of LiveData object (locationData). What is the proper way to do this in Kotlin. I also need to pass context to this this singleton.

class LocationViewModel extends ViewModel {
    private LiveData<Location> locationData = null;
 
    LiveData<Location> getLocation(Context context) {
        if (locationData == null) {
            locationData = new MyLocationListener(context);
        }
        return locationData;
    }
}

That’s my dummy implementation:

class LocationViewModel: ViewModel() {
    lateinit var locationData: MyLocationListener

    fun getLocation(context: Context): MyLocationListener {
        locationData = MyLocationListener(context)
        return locationData
    }

I would do it like this:

  class LocationViewModel: ViewModel(){
    var locationData: MyLocationListener? = null
        fun getLocation(context: Context) = locationData ? : synchronized(this) {
           MyLocationListener(context).also{
                locationData = it
            }
       }
} 

. I found this implementation online Kotlin singletons with argument. object has its limits | by Christophe Beyls | Medium

1 Like