Home > Software design >  How to prepend list in kotlin
How to prepend list in kotlin

Time:01-15

Hey I want to prepend item in list in kotlin. I am trying to add item but unfortunately, I am getting error, can someone guide me how to do that.

val prepareMutableLiveData: MutableLiveData<List<ConversationCount>> = MutableLiveData(
            emptyList()
        )

fun formatData() {
        val conversationCount = mutableListOf<ConversationCount>()
        viewModelScope.launch {
            dateRange.forEachIndexed { index, dateRangeValue ->
                val findData = data?.find {
                    dateRangeValue == it.dateObject
                }
                conversationCount.add(
                    ConversationCount(
                        setDay(dateRangeValue),
                        index,
                        findData != null
                    )
                )
            }
            prepareMutableLiveData.value = mutableListOf(conversationCount)   prepareMutableLiveData.value
        }
    }

I am getting error

Type mismatch.
Required:
ConversationCount
Found:
List<ConversationCount>?
Type mismatch.
Required:
List<ConversationCount>?
Found:
List<List<ConversationCount>?>
Type mismatch.
Required:
ConversationCount
Found:
MutableList<ConversationCount

enter image description here

I tried this

prepareMutableLiveData.value = conversationCount   prepareMutableLiveData.value

it gives error

Type mismatch.
Required:
ConversationCount
Found:
List<ConversationCount>

CodePudding user response:

Since conversationCount is already a List and your live data is also a list i.e MutableLiveData<List<ConversationCount>> you can simply use the code below .

prepareMutableLiveData.value = conversationCount   prepareMutableLiveData.value.orEmpty()

orEmpty() here is for null safety . you can also use !! but its not safe.

  •  Tags:  
  • Related