android - 伴随对象中的 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")
)
}
}
当我运行几次函数 updateDrawerProfiles 返回有效的列表大小。运行 x3 updateDrawerProfiles () | 输出:3 4 5
应该是 3 3 3。
当我将函数 updateDrawerProfiles 移动到伴生对象之外时 - 没关系。为什么会这样?
解决方案
应该是 3 3 3。
错误的。
DrawerUtils
同伴是单身人士。创建一次,对象保持存在。您将新值添加到exampleProfile
3 次,因此大小增长到 3、4 和 5 是有意义的。
请阅读此主题https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html
推荐阅读
- windows-10 - Windows10 是否会缩短在浏览器中制作的 webm 视频?
- java - 绘制的形状不显示在 JFrame 上
- aws-lambda - 部署到 AWS 时未调用无服务器 Lambda 授权程序
- c - C 编程:如何从文件中删除单个记录
- regex - 正则表达式出了什么问题?
- html - 使用单独的 svg 作为背景的最佳方法是什么?
- android - android studio org.json.JSON.typeMismatch
- node.js - 如何使用 NodeJs(和 ExpressJs?)REST 服务私有图像
- c# - WPF Datagrid,如何从 ControlTemplate 访问验证错误
- assembly - 在尝试将用户估算的分数相加时,Assembly-ax 总是返回相同的值。我究竟做错了什么?