Android 将 MutableLiveData<MutableSet>> 转换为 LiveData<Set>>

Android cast MutableLiveData<MutableSet>> to LiveData<Set>>

我正在使用可变阴影,我有一个类似

的东西
val selectedEntryIds: LiveData<Set<Long>>
    get() = _selectedProductIds

private val _selectedProductIds = MutableLiveData<MutableSet<Long>>(mutableSetOf())

但是我收到一条错误消息,指出类型不匹配。

像这样使用方差注释out

    val selectedEntryIds: LiveData<out Set<Long>>
        get() = _selectedProductIds

告诉编译器LiveData只会产生这样一个集合。检查:

https://kotlinlang.org/docs/generics.html#declaration-site-variance

您或许可以执行以下操作

val selectedEntryIds: LiveData<Set<Long>>
    get() = _selectedProductIds as LiveData<Set<Long>>

private val _selectedProductIds = MutableLiveData<MutableSet<Long>>(mutableSetOf())

关于将 MutableLiveData<..> 转换为常规 LiveData<..> 对象。