NiceToMytyuk
NiceToMytyuk

Reputation: 4317

How to cast one object to another object type? List<A> to List<B>?

I have two objects like:

@Entity(tableName = "punti_vendita")
class PuntiVendita(
    @PrimaryKey(autoGenerate = false)
    var cod: String,
    var desc: String
)

And

data class AutoComplete(
    var cod: String,
    var desc: String
)

Is there a way in Kotlin to merge the first object in the second one?

My api returns AutoComplete which then i insert in DB, the DB object is under PuntiVendita so i have to pass to my insert method the PuntiVendita object.

i was trying to do something like :

val puntiVendita = response.body()!! as List<PuntiVendita> but i get uncheked type warning (Unchecked cast: List to List) and i would prevent it without doing any @Suppress

Upvotes: 0

Views: 684

Answers (3)

Dmitry
Dmitry

Reputation: 344

You can't, it's different types

you may try something like

fun List<AutoComplete>.convert(): List<PuntiVendita>
{
    return this.map { PuntiVendita(it.cod, it.desc) }
}

fun test()
{
    val listA = listOf<AutoComplete>()
    val listB = listA.convert()
}

Upvotes: 0

cactustictacs
cactustictacs

Reputation: 19622

Your two classes have no connection to one another - they happen to have two fields of the same type with the same names, but that's a "coincidence", they have no relationship as far as the type system knows.

When you cast them, you're saying "hey by the way, I know this list says it holds AutoComplete objects, but you can treat them as PuntiVenditas instead - trust me."

The type system can't confirm that, it can't check it and verify you're doing the right thing, so it's giving you that warning - there's an unchecked cast here! And even if it works, if you (or the API) ever change one of those classes so you can't treat them as the same, the type system can't warn you about it. So it's warning you now, this is dangerous!

If you can't get the API to produce PuntiVendita objects directly, probably the safest thing is to create a function that takes one, and produces the other with the same values. If you do it in code (as opposed to, say, serialising to JSON and back into another type) you'll get the benefits of type checking and code validation and all that good stuff. Plus you get to control things like which properties are included, or converting their names if necessary

Upvotes: 1

Gurgen Arustamyan
Gurgen Arustamyan

Reputation: 187

You can use Gson to do that

gson.fromJson(gson.toJson(response.body()),object: TypeToken<List<PuntiVendita>>() {}.type )

Upvotes: 0

Related Questions