【发布时间】:2021-11-06 08:24:10
【问题描述】:
如何在 Kotlin 中像在 JavaScript 中一样将两个数据类合并为一个
const a = {name: "test A", age: 20};
const b = {...a, ...{city: "City Test"}}
现在我像这样从 api 接收数据
data class Explosive(
val id: Long,
val name: String,
val code: String?,
val decelerationCharge: Boolean
)
但是在本地数据库中我使用这个类
data class ExplosiveDB(
@PrimaryKey(autoGenerate = true) var id: Long = 0L,
@ColumnInfo(name = "explosive_id") val explosiveId: Long,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "code") val code: String?,
@ColumnInfo(name = "decelerationCharge") val decelerationCharge: Boolean
)
而我的问题是这段代码,因为我几乎必须重写所有内容
ExplosiveDB(
id = 0,
explosiveId = explosive.id,
name = explosive.name,
code = explosive.code,
decelerationCharge = explosive.decelerationCharge
)
我怎样才能避免这种情况?
任何链接、解释或 cmets 都会帮助我
【问题讨论】:
-
您在寻找交叉路口类型吗?联合代表非此即彼。
-
@MisterMiyagi,我更新了我的问题
-
你有两个数据类,你想用最少的样板代码将一个转换成另一个。这是你想要的吗?
-
@ArpitShukla,是的
标签: kotlin data-class