我希望使用返回而不是让,所以我编写了代码B,但代码B无法编译,我收到两个错误,为什么?
错误:(30,10)'返回'这里不允许
错误:(30,45)类型不匹配:推断类型是CityForecast?但预计CityForecast
代码A
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)
}
答案 0 :(得分:4)
convertToDomain
期待非空CityForecast
而非可空CityForecast?
。因此,使用let
是一种更好的方法。否则,您必须强行打开可空的city
,如下所示:
dataMapper.convertToDomain(city!!)
此外,如果你想从lambda返回,你必须使用qualified returns:
return@use dataMapper.convertToDomain(city!!)