Android 伴生对象中的val arrayListOf()返回无效值
我有密码:Android 伴生对象中的val arrayListOf()返回无效值,android,kotlin,Android,Kotlin,我有密码: class DrawerViewModel : ViewModel() { fun updateDrawerProfiles() { val example = DrawerUtils.exampleProfile example.add( DrawerAccount(3, "NEW Test") ) setDrawerProfiles(example) } } [运行示例代码]( ) 当我运行多次函数updat
class DrawerViewModel : ViewModel() {
fun updateDrawerProfiles() {
val example = DrawerUtils.exampleProfile
example.add( DrawerAccount(3, "NEW Test") )
setDrawerProfiles(example)
}
}
[运行示例代码](
)
当我运行多次函数updateDrawerProfiles时,返回列表的有效大小。
运行x3更新的AWERPROFILES();输出:
3.
4.
五,
应该是
3.
3.
三,
当我将函数updateDrawerProfiles移到伴生对象之外时——这是正常的。
为什么会这样
应该是3
错
drawerrutils
同伴是单身汉。创建一次,对象将保持存在。您将向exampleProfile
3次添加新值,因此将大小依次增加到3、4和5是有意义的
请读一些关于这个话题的书
应该是3
错
drawerrutils
同伴是单身汉。创建一次,对象将保持存在。您将向exampleProfile
3次添加新值,因此将大小依次增加到3、4和5是有意义的
请阅读一下这个话题我知道这是单身,但对我来说很奇怪。当我查看代码时,我看到从抽屉列表中获取值。exampleProfile到example,然后添加项。因此,当您调用
抽屉列表时,more Kotlin:)exampleProfile
您不是在创建新的ArrayList,而是在抽屉列表中获取对该ArrayList的引用。ok。现在我明白了。“瓦尔”骗了我。我更改arraylist的内容,而不是变量。是吗?val表示不能将新的arraylist重新分配给变量。这仍然意味着你可以将条目添加到列表中。我知道这是单例,但对我来说,这很奇怪。当我查看代码时,我看到从抽屉列表中获取值。exampleProfile到example,然后添加项。因此,当您调用抽屉列表时,more Kotlin:)exampleProfile
您不是在创建新的ArrayList,而是在抽屉列表中获取对该ArrayList的引用。ok。现在我明白了。“瓦尔”骗了我。我更改arraylist的内容,而不是变量。是吗?val表示不能将新的arraylist重新分配给变量。这仍然意味着您可以向列表中添加条目
class DrawerUtils {
companion object {
val exampleProfile = arrayListOf(
DrawerAccount(1, "Facebook"),
DrawerAccount(2, "Google")
)
}
}