我有一些东西在下面
class XDatabase {
private val _stateData = MutableStateFlow(XData())
val stateData: StateFlow<XData> get() = _stateData
}
class YDatabase {
private val _stateData = MutableStateFlow(YData())
val stateData: StateFlow<YData> get() = _stateData
}
我想确保XDatabase和YDatabase彼此一致,
所以我在 下面创建了一个接口class XDatabase: Database<XData> {
override val _stateData = MutableStateFlow(XData())
}
class YDatabase: Database<YData> {
override val _stateData = MutableStateFlow(YData())
}
interface Database<T> {
val _stateData: MutableStateFlow<T>
val stateData: StateFlow<T> get() = _stateData
}
但是我不能再设置我的_stateData
私有或保护,因为Kotlin的接口不允许这样做。还有办法设置吗?(例如,我想避免其他类意外地从这些类访问_stateData
可以声明_stateData作为私有的,您可以确保它只能在实现类中被访问。stateData属性提供可从外部访问的状态数据的只读视图。
interface Database<T> {
val stateData: StateFlow<T>
fun updateData(data: T)
}
class XDatabase : Database<XData> {
private val _stateData = MutableStateFlow(XData())
override val stateData: StateFlow<XData>
get() = _stateData
override fun updateData(data: XData) {
_stateData.value = data
}
}
class YDatabase : Database<YData> {
private val _stateData = MutableStateFlow(YData())
override val stateData: StateFlow<YData>
get() = _stateData
override fun updateData(data: YData) {
_stateData.value = data
}
}