我有代码:
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")
)
}
}
当我运行几次时,函数updateDrawerProfiles返回列表的有效大小。 运行x3 updateDrawerProfiles ()|输出: 3 4 5
应该是 3 3 3。
当我移动功能updateDrawerProfiles超出伴侣对象时-可以。 为什么会这样?
答案 0 :(得分:2)
应该是3 3 3。
错。
DrawerUtils
同伴是一个单例。创建一次,该对象保持存在。您要向exampleProfile
添加3次新值,因此将大小增大为3,然后是4,然后是5,是有意义的。
请对此主题https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html
进行一些阅读