ursus
02/28/2024, 4:20 PMdata class Form(
..
val fields: Fields
) {
data class Fields(
val personalNumber: InputField,
...
)
}
data class InputField(
val value: String,
..
}
this is my model
I want to update value
obviously its a copy of a copy of a copy, which is ugly, I want to stuff into a extension
private fun <T> Form.updatePersonalNumberValue(value: String): Form {
val field = fields.personalNumber.copy(value = value)
copy(fields = fields.copy(personalNumber = field)
}
works but obviously doesn't scale as I have 20 fields, is there a way to make this generic somehow?
private fun Form.updateFieldValue(selector: (Form.Fields) -> InputField, value: String) {
I was thinking something like this, a selector lambda
val field = selector(fields)
however how do I assign it back to the Form
? So seems like a dead end. It seems I can only do Fields -> Fields
lambda at best
Is this really the best you can do in kotlin?
form.updateFields {
copy(
personalNumber = personalNumber.copy(
value = "new personal number"
)
)
}
TLDR; is there a way to generically select a copy parameter?Youssef Shoaib [MOD]
02/28/2024, 4:21 PMLens
. I would recommend using something like Arrow Optics to generate those lenses for you either at compile-time or runtime.ursus
02/28/2024, 4:22 PMform.fields.personaNumber.value = x
ursus
02/28/2024, 4:23 PMupdateFields(
selector = { it.personalNumber },
updater = { it.copy(value = "x")}
)
Youssef Shoaib [MOD]
02/28/2024, 4:25 PMursus
02/28/2024, 4:26 PMcopy
for update
?Youssef Shoaib [MOD]
02/28/2024, 4:31 PMval personalNumberValueLens = Form::fields.asLens() andThen Fields::personalNumber.asLens() andThen InputField::value.asLens()
val form2 = form.with(personalNumberValueLens, "x")
Youssef Shoaib [MOD]
02/28/2024, 4:31 PMandThen
that uses properties directlyursus
02/28/2024, 4:32 PMcopy
calls 😕ursus
02/28/2024, 4:32 PMYoussef Shoaib [MOD]
02/28/2024, 4:41 PMursus
02/28/2024, 4:42 PMCLOVIS
02/28/2024, 5:23 PMKlitos Kyriacou
02/28/2024, 5:56 PMCLOVIS
02/28/2024, 5:58 PM