gpt4 book ai didi

kotlin - 如何使用return代替让Kotlin进行出租?

转载 作者:行者123 更新时间:2023-12-02 13:09:30 25 4
gpt4 key购买 nike

代码A来自https://github.com/antoniolg/Kotlin-for-Android-Developers/blob/master/app/src/main/java/com/antonioleiva/weatherapp/data/db/ForecastDb.kt

我希望使用返回而不是来完成,所以我编写了代码B,但是代码B无法编译,并且出现两个错误,为什么?

错误:(30,10)此处不允许“返回”

错误:(30,45)类型不匹配:推断的类型是CityForecast?但是CityForecast是预期的

代码

 override fun requestForecastByZipCode(zipCode: Long, date: Long) = forecastDbHelper.use {

val dailyRequest = "${DayForecastTable.CITY_ID} = ? AND ${DayForecastTable.DATE} >= ?"
val dailyForecast = select(DayForecastTable.NAME)
.whereSimple(dailyRequest, zipCode.toString(), date.toString())
.parseList { DayForecast(HashMap(it)) }

val city = select(CityForecastTable.NAME)
.whereSimple("${CityForecastTable.ID} = ?", zipCode.toString())
.parseOpt { CityForecast(HashMap(it), dailyForecast) }

city?.let { dataMapper.convertToDomain(it) }
}

代码B
 override fun requestForecastByZipCode(zipCode: Long, date: Long) = forecastDbHelper.use {

val dailyRequest = "${DayForecastTable.CITY_ID} = ? AND ${DayForecastTable.DATE} >= ?"
val dailyForecast = select(DayForecastTable.NAME)
.whereSimple(dailyRequest, zipCode.toString(), date.toString())
.parseList { DayForecast(HashMap(it)) }

val city = select(CityForecastTable.NAME)
.whereSimple("${CityForecastTable.ID} = ?", zipCode.toString())
.parseOpt { CityForecast(HashMap(it), dailyForecast) }

return dataMapper.convertToDomain(city)
}

最佳答案

convertToDomain期望使用非null的CityForecast而不是可空的CityForecast?。因此,使用let是更好的方法。否则,您必须像这样强制解开可为空的city:

dataMapper.convertToDomain(city!!)

此外,如果要从lambda返回,则必须使用 qualified returns:
return@use dataMapper.convertToDomain(city!!)

关于kotlin - 如何使用return代替让Kotlin进行出租?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47119460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com