类型不匹配:在预期天气时推断类型为 Unit
Type mismatch: inferred type is Unit when Weather was expected
我正在开发一个 Android 天气应用程序,但我收到了标题中描述的错误。导致此错误的函数是调用某些天气数据的存储库。我有一个名为 DataOrException 的助手 class,它是:
class DataOrException<T, Boolean, E>(
var data: T? = null,
var loading: Kotlin.Boolean? = null,
var e: E? = null
)
调用此 class 的函数是一个协程,它从存储库中获取天气信息,该存储库使用注入到 return class。这是函数:
suspend fun getWeather(cityQuery: String, units: String): DataOrException<Weather, Boolean, Exception> {
val response = try {
api.getWeather(query = cityQuery, units = units)
} catch (e: Exception) {
Log.d("REX", "getWeather: $e")
return DataOrException(e = e)
}
return DataOrException(data = response) //Error occurs here.
关于如何修复此错误的任何想法?
你在 WeatherApi
中的 getWeather
函数没有返回任何东西,所以它基本上是一个 kotlin Unit
。但是,在您的存储库 return DataOrException(data = response)
中,此处 data
应为 Weather
类型。这就是错误的原因。
解法:
Return Weather
来自 WeatherApi
函数 getWeather
& 保持其他一切不变。
interface WeatherApi {
@GET(value = "/cities/cityID=Chelsea")
suspend fun getWeather(@Query("q") query: String, @Query("units") units: String = "imperial") : Weather
}
或
================
通过更改为 : DataOrException<Unit, Boolean, Exception>
将 data
类型更改为 Unit
suspend fun getWeather(
cityQuery: String,
units: String
): DataOrException<Unit, Boolean, Exception> {
val response = try {
api.getWeather(query = cityQuery, units = units)
} catch (e: Exception) {
Log.d("REX", "getWeather: $e")
return DataOrException(e = e)
}
return DataOrException(data = response)
}
我正在开发一个 Android 天气应用程序,但我收到了标题中描述的错误。导致此错误的函数是调用某些天气数据的存储库。我有一个名为 DataOrException 的助手 class,它是:
class DataOrException<T, Boolean, E>(
var data: T? = null,
var loading: Kotlin.Boolean? = null,
var e: E? = null
)
调用此 class 的函数是一个协程,它从存储库中获取天气信息,该存储库使用注入到 return class。这是函数:
suspend fun getWeather(cityQuery: String, units: String): DataOrException<Weather, Boolean, Exception> {
val response = try {
api.getWeather(query = cityQuery, units = units)
} catch (e: Exception) {
Log.d("REX", "getWeather: $e")
return DataOrException(e = e)
}
return DataOrException(data = response) //Error occurs here.
关于如何修复此错误的任何想法?
你在 WeatherApi
中的 getWeather
函数没有返回任何东西,所以它基本上是一个 kotlin Unit
。但是,在您的存储库 return DataOrException(data = response)
中,此处 data
应为 Weather
类型。这就是错误的原因。
解法:
Return Weather
来自 WeatherApi
函数 getWeather
& 保持其他一切不变。
interface WeatherApi {
@GET(value = "/cities/cityID=Chelsea")
suspend fun getWeather(@Query("q") query: String, @Query("units") units: String = "imperial") : Weather
}
或
================
通过更改为 : DataOrException<Unit, Boolean, Exception>
data
类型更改为 Unit
suspend fun getWeather(
cityQuery: String,
units: String
): DataOrException<Unit, Boolean, Exception> {
val response = try {
api.getWeather(query = cityQuery, units = units)
} catch (e: Exception) {
Log.d("REX", "getWeather: $e")
return DataOrException(e = e)
}
return DataOrException(data = response)
}