在 Android 开发中,Kotlin 的数据类(Data Class)因其简洁性和自动生成的功能特性,成为了提升开发效率的利器。以下是我总结的 7 大核心妙用场景,配合代码示例助您快速掌握:
1️⃣ JSON 解析利器 → 网络请求模型
与 Retrofit/Moshi 完美配合,自动生成 equals()
/hashCode()
等基础方法:
data class UserResponse(
@Json(name = "user_id") val id: Long,
val name: String,
val email: String,
@Transient val tempToken: String? = null // 排除序列化
)
// Retrofit 接口直接返回
@GET("user/{id}")
suspend fun getUser(@Path("id") userId: Long): UserResponse
2️⃣ Room 数据库实体 → 数据持久化
结合 Room 时注意主键处理,copy()
方法简化更新操作:
@Entity(tableName = "notes")
data class NoteEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val title: String,
val content: String,
@ColumnInfo(name = "created_at"