为什么我不能将 `MutableState` 用作 属性 委托?

Why can't I use `MutableState` as a property delegate?

我正在尝试使用 MutableState 的实例作为 属性 委托。

这是我拥有的:

val countState = remember { mutableStateOf(0) }

这是我想要的:

var count by remember { mutableStateOf(0) }

但是,当我使用 by 关键字时,出现编译错误:

Type 'TypeVariable(T)' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate

怎么了?

要作为委托,MutableState 需要一个 getValue 函数(用于读取值)和一个 setValue 函数(用于写入值)。

当您通过 mutableStateOf 访问 MutableState 时,您使用导入:

import androidx.compose.runtime.mutableStateOf

但是,此导入不包括 MutableStategetValuesetValue 函数 - 它们在单独的文件中定义为扩展函数。要访问它们,需要显式导入该文件。

这本身通常不是问题 - 如果您键入:

countState.getValue(...)

Android Studio 会自动为您建议所需的导入。

但是,当您使用 by 关键字时,这是一个问题 - Android Studio 不会自动为您建议导入。相反,它会给出 cannot serve as a delegate 错误,而不会提示您需要做什么。

所以解决方法是自己手动添加扩展函数的导入:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

希望 IDE 团队中的某个人将来可以使这一点更加明显 - 自动建议导入将是理想的!