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

我是Kotlin的初学者。

以下代码来自Kotlin-for-Android开发人员,地址为https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-june-2017

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

看来,“ fun 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? } 

这基本上是这样做的:

 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