我正在开发新闻应用程序,但在我的 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>()
}
最佳答案
有同样的问题,我清除了构建,然后再次构建它,它成功了。
关于android - 预期类型不匹配 : inferred type is Any but List<SportNewsResponse>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58729282/