Oliver Song
Oliver Song

Reputation: 113

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

I'm using variable shadowing and I have a something like

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

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

However I get an error saying type mismatch.

Upvotes: 0

Views: 367

Answers (2)

Iv&#225;n Garza Bermea
Iv&#225;n Garza Bermea

Reputation: 742

You may be able to do the following

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

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

as to cast the MutableLiveData<..> into a regular LiveData<..> object.

Upvotes: 0

Eddie Lopez
Eddie Lopez

Reputation: 1139

Use the variance annotation out like this:

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

To tell the compiler that the LiveData will only produce such a set. Check:

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

Upvotes: 1

Related Questions