【问题标题】:union two data class into one in kotlin在kotlin中将两个数据类合并为一个
【发布时间】: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


【解决方案1】:

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

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

Try it yourself

(如果您愿意,也可以在此处使用命名参数)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2015-10-06
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多