如何使用 Koin 从 getter 函数 return 单例

How to return a Singleton from a getter function using Koin

我有以下 CurrentWeatherResponse class,其中包含使用 getter 到 return WeatherLocation() 实例的 location 字段使用 class 的构造函数参数。我将如何确保此 getter 始终 return 在模块文件中使用 Koin WeatherLocation class 的单例?

data class CurrentWeatherResponse(
    // Tells GSON that the "currently" field of the JSON returned by the
    // API should be tied with our CurrentWeatherEntry data class
    @SerializedName("currently")
    val currentWeatherEntry: CurrentWeatherEntry,
    val latitude:Double,
    val longitude:Double,
    val timezone:String
) {
    val location:WeatherLocation
        get() = WeatherLocation(latitude,longitude,timezone,currentWeatherEntry.time)
}

尝试使用代表。很简单 class:

class ReadOnlyDelegate<R, T>(val t:T) : ReadOnlyProperty<R, T> {
    override fun getValue(thisRef: R, property: KProperty<*>) = t
}

使用方法如下:

data class CurrentWeatherResponse(
    // Tells GSON that the "currently" field of the JSON returned by the
    // API should be tied with our CurrentWeatherEntry data class
    @SerializedName("currently")
    val currentWeatherEntry: CurrentWeatherEntry,
    val latitude:Double,
    val longitude:Double,
    val timezone:String) {

    val location:WeatherLocation by ReadOnlyDelegate(WeatherLocation(latitude, longitude, timezone, currentWeatherEntry.time))
}