【问题标题】:How can I add data by data class which is in list which is in another list? Or is there a better way?如何通过另一个列表中的列表中的数据类添加数据?或者,还有更好的方法?
【发布时间】:2022-01-06 15:32:14
【问题描述】:

这是我的声明:val areas = mutableListOf<MutableList<Point>>()

我的数据类:

data class Point(
    val accuracy: Double,
    val latitude: Double,
    val longitude: Double
) 

我的尝试:

areas.add(mutableListOf(mutableListOf(Point[0].copy(accuracy = 0.0, latitude = 0.0, longitude = 0.0)))

这可能有助于了解我需要什么:https://releases-f89f5.firebaseio.com/.json?fbclid=IwAR3Zso66lLJLQDX17K5LFuqByaJFLmKahg-TYrJF3BAZqhd3CbtFgqo9tug

我希望能够更改“Point”的数据并添加“Point”可变列表的可变列表。

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    areas 已经是外部列表。你有太多嵌套的mutableListOf()。这样做:

    areas.add(mutableListOf(Point[0].copy(accuracy = 0.0, latitude = 0.0, longitude = 0.0)))
    

    或者您可以使用+= 代替add 以避免跟踪额外的尾括号。

    areas += mutableListOf(
        Point[0].copy(accuracy = 0.0, latitude = 0.0, longitude = 0.0)
    )
    

    【讨论】:

    • 谢谢,但它告诉我:Classifier 'Point' does not have a companion object, and thus must be initialized here 当我尝试使用您的第一个示例时。
    • 什么是Point[0]?我假设您有一些名为 Point 的列表,您从中提取了一个值。好像您没有名为Point 的列表。如果您只是想从头开始创建一个新点而不是复制另一个点,请调用 Point 构造函数。
    • 这是一个数据类。你可以在我的问题中看到它。
    • Point 是一个类。我不知道Point[0] 是什么。 [0] 仅在您有一个容易混淆的名称为 Point 的 List 或 Array 时才有意义。
    • 您的问题代码采用了一些名为 Point (Point[0]) 的集合的第一个元素。然后它会复制该元素并更改一些值(在这种情况下所有这些值,如果您总是这样做,您可能只想构造一个新的Point)。然后它正在创建一个包含该副本的新列表,该副本被添加到areas 列表中(假设 Tenfour04 是正确的,并且您也不希望将其他列表也扔在那里)。如果这不是您想要的,您需要更详细地解释您在做什么,并可能显示更多代码
    猜你喜欢
    • 1970-01-01
    • 2021-09-05
    • 2014-01-21
    • 2016-12-16
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2015-04-18
    • 2022-06-15
    相关资源
    最近更新 更多