Aden Kurmanov
Aden Kurmanov

Reputation: 107

union two data class into one in kotlin

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

Upvotes: 0

Views: 567

Answers (1)

Arpit Shukla
Arpit Shukla

Reputation: 10493

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)

Upvotes: 3

Related Questions