如何在 kotlin 中添加列表

How to prepend list in kotlin

嘿,我想在 kotlin 的列表中添加项目。我正在尝试添加项目,但不幸的是,我遇到了错误,有人可以指导我如何操作吗?

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
        }
    }

我遇到错误

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

我试过了

prepareMutableLiveData.value = conversationCount + prepareMutableLiveData.value

它给出错误

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

由于 conversationCount 已经是一个列表,而您的实时数据也是一个列表,即 MutableLiveData<List<ConversationCount>> 您可以简单地使用下面的代码。

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

orEmpty() 这里是为了空安全。你也可以使用 !! 但它不安全。