https://kotlinlang.org logo
#announcements
Title
# announcements
k

KyooSik Lee

10/23/2019, 4:55 AM
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

Kirill Zhukov

10/23/2019, 4:59 AM
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

KyooSik Lee

10/23/2019, 5:01 AM
Thanks Kirill, what do you think about using objectMapper of Spring Boot?
k

Kirill Zhukov

10/23/2019, 5:01 AM
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

KyooSik Lee

10/23/2019, 5:03 AM
That was what I thought initially. Surely extension function should be best
I agree
Thank you, really helped
k

Kirill Zhukov

10/23/2019, 5:04 AM
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

bodiam

10/23/2019, 6:46 AM
something like MapStruct might be an option perhaps?
👍 2
s

Stephan Schroeder

10/23/2019, 12:56 PM
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.