Search code examples
kotlingenericskotlin-coroutinesandroid-mvvm

Change return type to 'T' errror


I override this function from ViewModelProvider.Factory but I get an error with the generic return type T. Why?

class NewsViewModelProviderFactory(
    val newsRepository: NewsRepository) : ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return NewsViewModel(newsRepository) as T
    }
}

Solution

  • It looks like the issue comes from the supertype of your type parameter T—that is, ViewModel?. According to the docs, create is declared in ViewModelProvider.Factory as

    open fun <T : ViewModel> create(modelClass: Class<T>): T
    

    Notice that it says <T : ViewModel>, not <T : ViewModel?>. This means that any consumer of a ViewModelProvider.Factory expects the create function to return a non-null ViewModel. However, the create function you've written could return null.

    If you changed your function to

    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return NewsViewModel(newsRepository) as T
    }
    

    that should alleviate the issue.