[英]union two data class into one in kotlin
我如何像在 JavaScript 中一樣在 Kotlin 中將兩個數據類合並為一個
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
)
我怎樣才能避免這種情況?
任何鏈接、解釋或評論都會幫助我
您可以創建一個簡單的擴展函數來簡化一個類到另一個類的轉換。
fun Explosive.toDatabaseModel() = ExplosiveDB(0, id, name, code, decelerationCharge)
(如果您願意,也可以在此處使用命名參數)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.