Kotlin .add 覆盖可变列表中列表的所有项目



我有一个包含可变列表的对象

object TrackingEventsList {
var EventDate: String = ""
var EventDescription: String = ""
}
object Waybill {
var WaybillNumber: String = ""
var OriginHub: String = ""
var TrackingEvents: MutableList<TrackingEventsList> = ArrayList()
}

当我尝试添加 Waybill.TrackingEvents 时,所有以前的实例都会被覆盖并复制最后添加的 TrackingEvent。

private fun fillTracking(events: NodeList) {
var list = TrackingEventsList
for (x: Int in 0 until events.length) {
var tName = (events.item(x) as Element).tagName
var event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
list.EventDate = event
}
if (tName == "EventDescription") {
list.EventDescription = event
}
}
Waybill.TrackingEvents.plus(list)
}

调用 fillTracking 3 次后的结果:

Waybill.TrackingEvents[0].EventDescription = "Event3"
Waybill.TrackingEvents[1].EventDescription = "Event3"
Waybill.TrackingEvents[2].EventDescription = "Event3"

Kotlin 中的object是一个单例,这意味着您无法初始化它,并且它全局只有一个实例。因此,当您更改单个实例的项目时,您将覆盖以前的数据。

您应该将它们(或至少 TrackingEventsList(更改为class。如果Waybill的变量是实例敏感的,那么它也需要一个类。但是在您添加的代码中,我找不到任何可以说您将其用作单例的内容,因此我将其保留为单例。

class TrackingEventsList (
var eventDate: String = "",
var eventDescription: String = "")
/**
* Also want to point out that this is still a singleton. If the data inside is instance-specific, you need to change it 
* to a class. 
*/
object Waybill {
var waybillNumber: String = ""
var originHum: String = ""
var trackingEvents: MutableList<TrackingEventsList> = ArrayList()
}
private fun fillTracking(events: NodeList) {
val item = TrackingEventsList()
for (x: Int in 0 until events.length) {
var tName = (events.item(x) as Element).tagName
var event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
item.eventDate = event
}
if (tName == "EventDescription") {
item.eventDescription = event
}
}
Waybill.trackingEvents.add(item)
}

你应该研究一下 Kotlin 的命名约定;字段永远不会以大写字母开头,除非它是一个静态常量(在这种情况下它是全大写的(。

由于TrackingEventsList是一个对象,这意味着它是一个单例(或只有一个实例(。 当您完成循环时,您始终在更新TrackingEventsList对象的同一实例。

TrackingEventsList改为:

data class TrackingEventsList(var eventDate: String, var eventDescription: String)

每次循环时创建一个新实例,然后将其添加到最后的列表中:

private fun fillTracking(events: NodeList) {
var eventDate: String = ""
var eventDescription: String = ""
for (x: Int in 0 until events.length) {
val tName = (events.item(x) as Element).tagName
val event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
eventDate = event
}
if (tName == "EventDescription") {
eventDescription = event
}
}
Waybill.TrackingEvents.plus(TrackingEventsList(eventDate, eventDescription))
}

相关内容

  • 没有找到相关文章

最新更新