I have a data class foo ```kotlin data class Foo( ...
# announcements
k
I have a data class foo
Copy code
kotlin
data class Foo(
    val a: Int,
    val b: String,
    val c: Int
    val d: Int
) {}
And I have another data class partialFoo, where I have partial fields of foo
Copy code
kotlin
data class PartialFoo(
    val a: Int,
    val b: String
) {}
Is there any way that I can copy the fields of class instance of
Foo
to class instance of
PartialFoo
?
k
nothing magical that I can think of
extension function
Foo.toPartialFoo()
might the most idiomatic
Also could use inheritance but I’d avoid it
depends on your use case of course
k
Thanks Kirill, what do you think about using objectMapper of Spring Boot?
k
not familiar
quick google tells me it’s part of
jackson
you could serialize your
Foo
object to json and then deserialize it to
PartialFoo
would advice against that heh
for the purposes of what you are trying to do I don’t think it’s worth doing serialization twice
👍 1
k
That was what I thought initially. Surely extension function should be best
I agree
Thank you, really helped
k
np
another big problem with using serialization in this case is maintenance. if signature of
Foo
or
PartialFoo
changes you won’t catch until in runtime or in unit tests if you have them. You could remedy that by using hardcoded serialized names but that’s just too much trouble and still doesn’t prevent someone from deleting the field or changing the type.
with extension function you have compile time safety
let compiler help you 🙂
b
something like MapStruct might be an option perhaps?
👍 2
s
just stating the obvious, but your solution - if you ever find one - might well be more complex and definitely less idiomatic than a bunch of assignments in a mapper method.