ComposeUI中的类与数据类
基本概念
Kotlin中类与数据类的基本概念和区别。
- Name
数据类(data class)
- Type
- data class
- Description
- 自动生成equals()/hashCode()
- 自动生成toString()
- 自动生成copy()
- 适合表示数据模型
- Name
普通类(class)
- Type
- class
- Description
- 需手动实现方法
- 支持继承
- 可以有状态
- 适合复杂业务逻辑
类与数据类示例
// 数据类示例
data class Person(
val name: String,
val age: Int
)
// 普通类示例
class Animal(
val name: String,
val species: String
)
// 继承示例
class Dog(
name: String,
val breed: String
) : Animal(name, species = "Dog")
ComposeUI中的应用
在ComposeUI中使用类与数据类的常见场景。
- Name
界面状态
- Type
- state
- Description
- 状态提升
- 状态托管
- 重组作用域
- 生命周期
- Name
数据模型
- Type
- models
- Description
- UI状态定义
- 数据绑定
- 状态更新
- 单向数据流
ComposeUI应用示例
// UI状态数据类
data class UserUiState(
val name: String = "",
val age: Int = 0,
val isLoading: Boolean = false
)
// 可组合函数
@Composable
fun UserScreen(
uiState: UserUiState,
onAgeIncrement: () -> Unit
) {
Column {
Text("用户名: ${uiState.name}")
Text("年龄: ${uiState.age}")
Button(onClick = onAgeIncrement) {
Text("增加年龄")
}
}
}
// ViewModel类
class UserViewModel : ViewModel() {
private val _uiState = MutableStateFlow(UserUiState())
val uiState: StateFlow<UserUiState> = _uiState.asStateFlow()
fun incrementAge() {
_uiState.update { currentState ->
currentState.copy(age = currentState.age + 1)
}
}
}
属性与方法
类与数据类中的属性和方法定义。
- Name
属性类型
- Type
- properties
- Description
- var/val属性
- 延迟属性
- 委托属性
- 伴生对象
- Name
方法类型
- Type
- methods
- Description
- 成员方法
- 扩展方法
- 运算符重载
- 高阶函数
属性与方法示例
data class Temperature(
var celsius: Double
) {
// 计算属性
val fahrenheit: Double
get() = celsius * 9/5 + 32
// 方法
fun reset() {
celsius = 0.0
}
companion object {
fun fromFahrenheit(value: Double): Temperature {
return Temperature((value - 32) * 5/9)
}
}
}
// 扩展方法
fun Temperature.toCelsiusString(): String {
return "$celsius°C"
}
最佳实践
类与数据类使用的推荐做法。
- Name
选择建议
- Type
- recommendations
- Description
- 不可变vs可变
- 继承vs组合
- 状态管理
- 内存优化
- Name
常见问题
- Type
- issues
- Description
- 重组优化
- 状态提升
- 副作用处理
- 性能考虑
最佳实践示例
// UI状态应该是不可变的
data class ScreenState(
val items: List<Item>,
val isLoading: Boolean,
val error: String?
)
// 使用密封类处理状态
sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val message: String) : Result<Nothing>()
object Loading : Result<Nothing>()
}
// 状态托管
class MyViewModel : ViewModel() {
private val _state = MutableStateFlow(ScreenState())
val state = _state.asStateFlow()
fun loadData() {
viewModelScope.launch {
_state.update { it.copy(isLoading = true) }
try {
// 加载数据
} catch(e: Exception) {
_state.update {
it.copy(error = e.message)
}
}
}
}
}