我的 MutableList 的添加功能不起作用

Add Function of my MutableList doesn't work

所以我得到了这段代码,但不知何故 "add" 函数不起作用。 "permits" 列表没问题,if-case 也被触发。但是最后的 "Log" 仍然显示 "null" for permits_modulated。有什么想法吗?

val permits: List<Schueler> = gson.fromJson(body, Array<Schueler>::class.java).toList()
val permits_modulated: MutableList<Schueler>? = null
for (permit in permits) {
    Log.d("permit in permits", permit.toString() + " " + permit.vorname)
    if (permit.vorname == name) {
        permits_modulated?.add(permit)
        Log.d("permit.vorname == name", permit.toString() + " " + permit.vorname)
        Log.d("permit_modulated in if", permits_modulated.toString())
    }
}

你的 MutableList? 因为这一行总是会是空的:

val permits_modulated : MutableList<Schueler>? = null

这表示 "create a val (which cannot be changed) called permits_modulated, of type nullable MutableList, and set its value to null"。

为了解决这个问题,您可以将其声明为具有非空值,并从类型中删除可空性:

val permits_modulated = mutableListOf<Scheduler>()

或:

val permits_modulated: MutableList<Scheduler> = mutableListOf()

然后,当您添加时,您可以忽略可空性,因为 permits_modulated 将始终有一个不为空的值:

 permits_modulated.add(permit)