为什么在视图模型中声明变量时使用下划线 kotlin 约定

Why use underscore kotlin convention when declaring variables in view model

在 android 蓝图示例的视图模型中,Google 使用了以下模式:

private val _dialog = MutableLiveData<Dialog>()
val dialog : LiveData<FindaDialogFragment> = _dialog

我搜索了 Google 原因。总之,我们限制了访问权限,使片段和活动无法修改 viewModel 中的数据。

我理解但无法同情。真的只有一个原因吗? 如果是这样,viewModel 中的代码将更长以限制对变量的访问。


private val name = MutableLiveData<String>()

此外,在 2 向数据绑定中,仅使用 MutableLiveData。 这不合逻辑。

我想知道使用这个模式是否还有其他原因。

Is there really only one reason?

是的。

If so, the code will be longer in viewModel to restrict access to variables.

是的。如果你不想,你不必使用它,并且可以记录它不打算被修改。

In 2-way data binding, only MutableLiveData is used. This is not logical.

是的; 2路数据绑定需要修改数据,所以需要MutableLiveData.