在科特林中将两个数据 class 合并为一个

union two data class into one in kotlin

如何在 Kotlin 中将两个数据 class 合并为一个,就像在 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
)

但是在本地数据库中我使用这个class

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
    )

我怎样才能避免这种情况?

任何链接、解释或评论都会对我有所帮助

您可以创建一个简单的扩展函数来简化一个 class 到另一个的转换。

fun Explosive.toDatabaseModel() = ExplosiveDB(0, id, name, code, decelerationCharge)

Try it yourself

(如果你愿意,也可以在这里使用命名参数)