Kotlin - Type mismatch required collection found list

Viewed 5964

I need to append two list but it say me:

type mismatch required collection found list

It is like bellow:

val list: List<Cohort> = ArrayList()
private fun fillFromDao() {
    val notesObserver: Observer<ArrayList<Cohort?>?>? =
        Observer { cohort: ArrayList<Cohort?>? ->
                list.toMutableList().addAll(cohort)
        }
    if (notesObserver != null) {
        otherDialogFragmentViewModel.fetchIsFree()?.observe(this, notesObserver)
        otherDialogFragmentViewModel.fetchHasCertificate()?.observe(this, notesObserver)
    }
}
2 Answers

Two changes:

val list: List<Cohort?> = ArrayList()    ----> add '?' after Cohort
    private fun fillFromDao() {
        val notesObserver: Observer<ArrayList<Cohort?>?>? =
            Observer { cohort: ArrayList<Cohort?>? ->
                    list.toMutableList().addAll(cohort!!) ----> add '!!' after Cohort
            }
        if (notesObserver != null) {
            otherDialogFragmentViewModel.fetchIsFree()?.observe(this, notesObserver)
            otherDialogFragmentViewModel.fetchHasCertificate()?.observe(this, notesObserver)
        }
    }

list variable of type List<Cohort>, but notesObserver value type is ArrayList<Cohort?>: so notesObserver value can have nullable elements.

Thus either list variable should accept nullable or notesObserver should not have nullable values.

Related