suspend fun safeApiCall(
apiCall: () -> Call<WeatherData>
): Resource<WeatherData> {
apiCall.enqueue() //error Unresolved reference: enqueue
}在上面的代码中,() -> Call<WeatherData>的含义是什么,它与Call<WeatherData>有何不同?
发布于 2020-09-30 12:27:56
是的,在@ADM链接的https://kotlinlang.org/docs/reference/lambdas.html#function-types部分解释了语法。
基本上,apiCall的类型是一个没有参数的函数( (),比如调用someFunction()),它返回(->)一个带有Call<WeatherData>类型的结果。
fun apiCall(): Call<WeatherData>但您可以传递任何与该签名匹配的函数(相同的参数类型、相同的返回类型)。这意味着你也可以通过兰巴达
safeApiCall({
doStuff()
doMoreStuff()
doThingThatReturnsAWeatherDataCall()
})(当lambda是唯一可以从括号中移出的参数时,我只想说明您将它作为参数传入)
如果在某个地方声明了一个与签名匹配的函数,则可以将对该函数的引用传递给
fun coolWeatherFunction(): Call<WeatherData>
safeApiCall(this::coolWeatherFunction)(您可以删除this,只需显示如何引用特定实例或类上的函数)
它有时会更易读
"1 2 3 4 5".split(' ').map(String::toDouble).forEach(::println)
1.0
2.0
3.0
4.0
5.0https://stackoverflow.com/questions/64137216
复制相似问题