https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

04/07/2021, 4:45 PM
is there any way to simplify this?
Copy code
update( B(firstField = objA.name, secondField = objB.surname) )
into something similar to this? (it doesn’t work)
Copy code
update( ::objA )
given that the two classes have the same structure but just different property names? so that I don’t need to manually specify each field?
Copy code
val objA = A("John", "Walker")

fun update(obj : B) {
    ...
}

data class A (
    val name : String
    val surname : String
)

data class B (
    val firstField : String
    val secondField : String
)
N.B. I cannot modify the classes definition, by extending or implementing interfaces
r

Roukanken

04/07/2021, 4:51 PM
My question is, if this was possible to make work what would you expect to happen if someone flips the order of B's or A's properties?
☝️ 1
because that would break your whole code...
if you say the classes hold same data, than easiest way is to just make function
A.toB()
which creates
B
from
A
, and just use that everywhere
(so you would call it like
update(objA.toB())
)
d

Daniele B

04/07/2021, 4:55 PM
yes, true, I was just wondering if Kotlin provides something like that, based on the property order, but I guess not
r

Roukanken

04/07/2021, 4:56 PM
afaik not, and even if it did - it's not a good idea, property order changes, boom whole thing stops working and you wouldn't even see what went wrong
d

Daniele B

04/07/2021, 5:01 PM
yes, I see your point, but in some cases, this would be very handy
e

ephemient

04/07/2021, 5:57 PM
is this a good idea? no.
😂 1
d

Daniele B

04/07/2021, 7:16 PM
definitely not a very concise code, but interesting to see, thanks!
2 Views