I have a data class MyDTO
that takes several parameters, but in one place where I call it, some parameters are the same. At the moment, I have a function that looks like this:
fun createDTO(f: Foo): MyDTO {
val a = f.foo()
val b = f.bar()
val c = f.baz()
return MyDTO(a, a, b, c, b, c)
}
Is there a more succinct way to do this? I especially like expression bodies, but I can’t do this:
fun createDTO(f: Foo) = MyDTO(f.foo(), f.foo(), f.bar(), f.baz(), f.bar(), f.baz())
because foo
, bar
and baz
are expensive and/or have side-effects, and therefore should only be called once.
I was thinking along the lines of:
data class MyDTO(val x1: Int, val x2: Int, val y1: Int, val y2: Int, val z1: Int, val z2: Int)
fun createDTO(f: Foo) = MyDTO(f.foo(), x2, f.bar(), f.baz(), y1, y2)
but of course I can’t access the properties of MyDTO until I’ve finished creating the instance.