如何在Kotlin中使用return而不是let?

时间:2017-11-05 08:05:22

标签: kotlin

代码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

代码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)
    }

1 个答案:

答案 0 :(得分:4)

convertToDomain期待非空CityForecast而非可空CityForecast?。因此,使用let是一种更好的方法。否则,您必须强行打开可空的city,如下所示:

dataMapper.convertToDomain(city!!)

此外,如果你想从lambda返回,你必须使用qualified returns

return@use dataMapper.convertToDomain(city!!)