你能解释一下有趣的requestByZipCode吗?

时间:2017-07-14 02:41:24

标签: android kotlin

我是Kotlin的初学者。

以下代码来自https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-june-2017

的Kotlin-for-Android-Developers

你能解释一下有趣的 requestByZipCode 吗?这很难理解。

似乎“有趣的requestByZipCode(zipCode:Long,days:Int):ForecastList = requestToSources {”是方便的代码,我不知道是否有完整代码的乐趣“有趣的requestByZipCode(zipCode:Long,days:Int)...... “很容易理解。

class ForecastProvider(val sources: List<ForecastDataSource> = ForecastProvider.SOURCES) {

    companion object {
        val DAY_IN_MILLIS = 1000 * 60 * 60 * 24
        val SOURCES by lazy { listOf(ForecastDb(), ForecastServer()) }
    }

    fun requestByZipCode(zipCode: Long, days: Int): ForecastList = requestToSources {
        val res = it.requestForecastByZipCode(zipCode, todayTimeSpan())
        if (res != null && res.size >= days) res else null
    }

    private fun <T : Any> requestToSources(f: (ForecastDataSource) -> T?): T = sources.firstResult { f(it) }

}



interface ForecastDataSource {
    fun requestForecastByZipCode(zipCode: Long, date: Long): ForecastList?
    fun requestDayForecast(id: Long): Forecast?
}



data class ForecastList(val id: Long, val city: String, val country: String, val dailyForecast: List<Forecast>) {
    val size: Int
        get() = dailyForecast.size
    operator fun get(position: Int) = dailyForecast[position]
}


interface ForecastDataSource {
    fun requestForecastByZipCode(zipCode: Long, date: Long): ForecastList?
    fun requestDayForecast(id: Long): Forecast?

}

1 个答案:

答案 0 :(得分:1)

这基本上是这样做的:

fun requestByZipCode(zipCode: Long, days: Int): ForecastList {
    return sources.firstResult {
        val res = it.requestForecastByZipCode(zipCode, todayTimeSpan())
        if (res != null && res.size >= days) res else null
    }
}

通过查看存储库,firstResult扩展函数将是:

fun requestByZipCode(zipCode: Long, days: Int): ForecastList {

        for (element in sources) {
            val res = element.requestForecastByZipCode(zipCode, todayTimeSpan())
            val result = if (res != null && res.size >= days) res else null
            if (result != null) return result
        }
        throw NoSuchElementException("No element matching predicate was found.")
 }

由于列表中的Extension Function,您可能无法理解它:https://kotlinlang.org/docs/reference/extensions.html