英文:
Android Jetpack compose, field expose
问题
val removingPluggableScreens: Boolean get() = _removingPluggableScreens.value
与 val removingPluggableScreens: Boolean = _removingPluggableScreens.value
之间的区别在于以下部分:
第一种方式(使用get())允许您创建一个只读属性,每次访问 removingPluggableScreens
时都会调用 _removingPluggableScreens.value
来获取最新值。这意味着它会在每次访问时动态获取 _removingPluggableScreens.value
的值。
第二种方式(不使用get())创建了一个简单的只读属性,它在初始化时获取 _removingPluggableScreens.value
的值,然后将其存储在 removingPluggableScreens
中。这意味着 removingPluggableScreens
的值在初始化后不会再随 _removingPluggableScreens.value
的更改而更新。
因此,第一种方式始终提供了最新的 _removingPluggableScreens.value
,而第二种方式只提供了初始值。选择哪种方式取决于您的需求,如果需要在每次访问时获取最新值,使用第一种方式更合适。
英文:
I have a question about this code,
private val _removingPluggableScreens = mutableStateOf(false)
val removingPluggableScreens: Boolean get() = _removingPluggableScreens.value
fun updateRemovingPluggableScreens(shouldRemovePluggableScreens: Boolean) {
if (shouldRemovePluggableScreens != _removingPluggableScreens.value) {
_removingPluggableScreens.value = shouldRemovePluggableScreens
}
}
The code is working fine as expected, but if I change the code this way-- without get() for removingPluggableScreens field it does not work as expected,
private val _removingPluggableScreens = mutableStateOf(false)
val removingPluggableScreens: Boolean = _removingPluggableScreens.value
fun updateRemovingPluggableScreens(shouldRemovePluggableScreens: Boolean) {
if (shouldRemovePluggableScreens != _removingPluggableScreens.value) {
_removingPluggableScreens.value = shouldRemovePluggableScreens
}
}
When I observe the state like this, it's not working correctly if I choose the second approach, but it works fine if I choose the first approach:
val removingPluggableScreens = viewModel.removingPluggableScreens
if (removingPluggableScreens) {
// do sth here
}
Simply, I want to know the differences between val removingPluggableScreens: Boolean get() = _removingPluggableScreens.value
and val removingPluggableScreens: Boolean = _removingPluggableScreens.value
Thanks in advance.
答案1
得分: 1
当您给变量赋值时,这仅发生一次,在您的情况下是在声明时。将来,您的代码中的这两个变量不以任何方式相关。
当您指定一个getter时,每次读取removingPluggableScreens
的值时都会调用它。在您的情况下,这个值将始终与_removingPluggableScreens.value
匹配。
英文:
When you assign a value to a variable, this happens only once, in your case, when you declare it. And in the future, these 2 variables in your code are not related in any way.
When you specify a getter, When you specify a getter, it is called every time the value of the removingPluggableScreens
is read. And in your case this value will always match the _removingPluggableScreens.value
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论