首页 > 解决方案 > 伴随对象中的 val arrayListOf() 返回无效值

问题描述

我有代码:

class DrawerViewModel : ViewModel() {

    fun updateDrawerProfiles() {
        val example = DrawerUtils.exampleProfile
        example.add(  DrawerAccount(3, "NEW Test") )
        setDrawerProfiles(example)
    }

}
class DrawerUtils {

    companion object {

        val exampleProfile = arrayListOf(
            DrawerAccount(1, "Facebook"),
            DrawerAccount(2, "Google")
        )

    }
}

[运行示例代码](https://play.kotlinlang。组织/#gYXJyYXlMaXN0T2YoXG4gICAgICAgICAgICBEcmF3ZXJBY2NvdW50KDEsIFwiRmFjZWJvb2tcIiksXG4gICAgICAgICAgICBEcmF3ZXJBY2NvdW50KDIsIFwiR29vZ2xlXCIpXG4gICAgICAgIClcbiAgICAgIFxuICAgIH1cbn1cbmRhdGEgY2xhc3MgRHJhd2VyQWNjb3VudCh2YXIgaWQ6IEludCwgdmFyIG5hbWU6IFN0cmluZyApXG5cbiJ9 )

当我运行几次函数 updateDrawerProfiles 返回有效的列表大小。运行 x3 updateDrawerProfiles () | 输出:3 4 5

应该是 3 3 3。

当我将函数 updateDrawerProfiles 移动到伴生对象之外时 - 没关系。为什么会这样?

标签: androidkotlin

解决方案


应该是 3 3 3。

错误的。

DrawerUtils同伴是单身人士。创建一次,对象保持存在。您将新值添加到exampleProfile3 次,因此大小增长到 3、4 和 5 是有意义的。

请阅读此主题https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html


推荐阅读