Search code examples
androidkotlinmvvmdata-binding

Smart Cast is not possible in Kotlin


I am uning MVVM pattern when i call api in activity from ViewModel its always throwing me with Error

Smart cast to 'MainActivityViewModel' is impossible, because 'binding.mainModel' is a complex expression    

Following is the my ViewMode:

class MainActivityViewModel(private val api: SearchAPI) : BaseViewModel() {

private var query: String = ""
    get() = if (field.isEmpty()) "MVVM" else field

private val _refreshing: NotNullMutableLiveData<Boolean> = NotNullMutableLiveData(false)
val refreshing: NotNullMutableLiveData<Boolean>
    get() = _refreshing

lateinit var  _items: NotNullMutableLiveData<RetrofitWrapper>
val items: NotNullMutableLiveData<RetrofitWrapper>
    get() = _items

fun getMainPageData() {
    val params = mutableMapOf<String, String>().apply {
        this["version"] = "v1"
        this["locale"] = "en"
        this["platform"] = "android"
    }

    addToDisposable(api.getHomePageDetail(params).with()
        .doOnSubscribe { _refreshing.value = true }
        .doOnSuccess { _refreshing.value = false }
        .doOnError { _refreshing.value = false }
        .subscribe({
            _items.value = it
        }, {
            // handle errors
        })
    )
}

}   

And following is my MainActivity:

class MainActivity : BindingActivity<ActivityMain2Binding>() {
    override fun getLayoutResId(): Int {
        return R.layout.activity_main2
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.mainModel = getViewModel()
        binding.setLifecycleOwner(this)
        binding.mainModel.getMainPageData()

    }
    }

Your Help on this matter highly appreciated, do let me know why this is happening to me.


Solution

  • binding.mainModel is a mutable, nullable variable.

    Generated binding setter method code will look something like this :

    public void setViewModel(@Nullable MainActivityViewModel viewModel) { ... }

    When you call binding.mainModel.getMainPageData() it cannot infer that the variable is not null.

    You can either do :

    binding.mainModel!!.getMainPageData()

    or more safely :

    binding.mainModel?.getMainPageData()