Home > Back-end >  union two data class into one in kotlin
union two data class into one in kotlin

Time:11-06

How can i union two data class into one in Kotlin like in JavaScript

const a = {name: "test A", age: 20};
const b = {...a, ...{city: "City Test"}}

Now i receive data from api like this

data class Explosive(
    val id: Long,
    val name: String,
    val code: String?,
    val decelerationCharge: Boolean
)

But in local db i use this 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
)

And my problem is this code, because I have to rewrite almost everything

ExplosiveDB(
        id = 0,
        explosiveId = explosive.id,
        name = explosive.name,
        code = explosive.code,
        decelerationCharge = explosive.decelerationCharge
    )

How can I avoid this?

Any links, explanations or comments will help me

CodePudding user response:

You can create a simple extension function to simplify conversion of one class to another.

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

Try it yourself

(You can also use named arguments here if you like to)

  • Related