我正在开发新闻应用程序,并且在MainViewModel.kt类中遇到以下错误 类型不匹配:推断的类型为“除列表以外的其他”?是预期的
在我的MainViewModel.kt下面
class MainViewModel(
private val sportNewsInterface: SportNewsInterface
) : ViewModel(), CoroutineScope {
// Coroutine's background job
private val job = Job()
// Define default thread for Coroutine as Main and add job
override val coroutineContext: CoroutineContext = Dispatchers.Main + job
private val showLoading = MutableLiveData<Boolean>()
private val sportList = MutableLiveData <List<SportNewsResponse>>()
val showError = SingleLiveEvent<String>()
fun loadNews() {
// Show progressBar during the operation on the MAIN (default) thread
showLoading.value = true
// launch the Coroutine
launch {
// Switching from MAIN to IO thread for API operation
// Update our data list with the new one from API
val result = withContext(Dispatchers.IO) { sportNewsInterface.getNews()
}
// Hide progressBar once the operation is done on the MAIN (default) thread
showLoading.value = false
when (result) {
is UseCaseResult.Success<*> -> {
sportList.value = result.data
}
is UseCaseResult.Error -> showError.value = result.exception.message
}
}
}
override fun onCleared() {
super.onCleared()
// Clear our job when the linked activity is destroyed to avoid memory leaks
job.cancel()
}
}
UserCaseResult.kt以下
sealed class UseCaseResult<out T : Any> {
class Success<out T : Any>(val data: T) : UseCaseResult<List<SportNewsResponse>>()
class Error(val exception: Throwable) : UseCaseResult<Nothing>()
}
答案 0 :(得分:3)
遇到了同样的问题,我清除了构建,然后再构建了一次,并且成功了。
答案 1 :(得分:0)
看看您的Success
类。您正在使用通用类型val data
定义T
,该类型由Any
界定。在when
块中,当您要检查它是否为UseCaseResult.Success
的实例时,您正在使用星型投影,该星型投影会导致编译器以上限来推断结果:{{ 1}}。因此,UseCaseResult.Success<Any>
的类型将被推断为result.data
。
解决方案是:
如果Any
仅具有列表类型的数据,则应忽略通用类型(当前UseCaseResult.Success
类定义中的通用类型没有意义):
Success
或:
class Success(val data: List<SportNewsResponse>) : UseCaseResult<List<SportNewsResponse>>()
或者您可以简单地将when子句更改为此:
class Success<out T: Any>(val data: List<T>) : UseCaseResult<List<T>>()