David Kubecka
02/23/2023, 3:36 PMdata class Coordinates(val x: Int, val y: Int)
// NOTE: I cannot change this as it comes from 3rd party system.
data class CoordinatesAndColor(val color: String, val x: Int = 0, val y: Int = 0)
// is actually passed from outside so it can be null
val coords: Coordinates? = Coordinates(1, 1)
// now I would like to do something akin to this (in "pseudo-code")
CoordinatesAndColor(color = "red").apply {
// if coords is null the default values should be used
coords?.let {
x = it.x
y = it.y
}
}
// currently the only way I know is this
CoordinatesAndColor(color = "red", x = coords?.x ?: 0, y = coords?.y ?: 0)
Any ideas?Joffrey
02/23/2023, 3:44 PMx
and y
properties, which solves the problem altogether. It would also allow to use methods/extensions of Coordinates
more easily with CoordinatesAndColor
instances. You could still define x
and y
extension properties that delegate to the underlying coordinates object.David Kubecka
02/23/2023, 3:47 PMCoordinatesAndColor
(updating the post)Joffrey
02/23/2023, 4:00 PMx
and y
like in your last example, or you use an if
statement to call the 1-arg constructor or the 3-arg constructor based on the nullilty of `coords`:
// custom factory function
fun CoordsAndColor(color: String, coords: Coordinates?) = if (coords == null) {
CoordsAndColor(color = color)
} else {
CoordsAndColor(color = color, x = coords.x, y = coords.y)
}
Klitos Kyriacou
02/23/2023, 4:15 PMcopy
function could be used:
CoordinatesAndColor(color = "red").let {
if (coords == null)
it
else
copy(x = it.x, y = it.y)
}
If it's actually more complicated, with more parameters and more conditions, you might want to create a builder.Joffrey
02/23/2023, 4:17 PMKlitos Kyriacou
02/23/2023, 4:21 PMCoordinatesAndColor(color = "red", x = coords?.x ?: 0, y = coords?.y ?: 0)
It could have been useful if the language allowed something like:
CoordinatesAndColor(color = "red", x = coords?.x ?: default, y = coords?.y ?: default)
Joffrey
02/23/2023, 4:27 PMKlitos Kyriacou
02/23/2023, 4:42 PMJacob
02/23/2023, 4:47 PMval coords = coordsFromOutside() ?: Coordinates(0,0)
CoordinatesAndColor("red", coords.x, coords.y)
Klitos Kyriacou
02/23/2023, 4:48 PMDavid Kubecka
02/24/2023, 9:45 AMJoffrey
02/24/2023, 5:23 PMif
and 2 different constructor calls depending on the case. Using a combination of nested `let`/`if`/`copy` is a lot of cognitive overhead IMO.David Kubecka
02/25/2023, 9:17 AMcopy
leads to less code duplication.