Is there any way to deconstruct in a deconstruct?
# general-advice
z
Is there any way to deconstruct in a deconstruct?
My current code looks like
Copy code
properties.forEachIndexed { index, (group, name, parameters, value) ->
    when (index) {
        0 -> require(name.value == "BEGIN" && value.value == "VCARD")
        1 -> require(name.value == "VERSION" && value.value == "4.0")
        properties.lastIndex -> require(name.value == "END" && value.value == "VCARD")
    }
}
What I'd like is something like
Copy code
properties.forEachIndexed { index, (group, (name), parameters, (value)) ->
    when (index) {
        0 -> require(name == "BEGIN" && value == "VCARD")
        1 -> require(name == "VERSION" && value == "4.0")
        properties.lastIndex -> require(name == "END" && value == "VCARD")
    }
}
The closest I can get requires me to provide an
operator fun component1()
on the value class, and then deconstruct them separately
Copy code
properties.forEachIndexed { index, (group, propertyName, parameters, propertyValue) ->
    val (name) = propertyName
    val (value) = propertyValue
    when (index) {
        0 -> require(name == "BEGIN" && value == "VCARD")
        1 -> require(name == "VERSION" && value == "4.0")
        properties.lastIndex -> require(name == "END" && value == "VCARD")
    }
}
Most of my value classes simply have the value name be
value
or the type of the value, like
Copy code
value class StringPropertyValue(val value: String)
or
value class StringPropertyValue(val string: String)
Maybe this is just a naming issue?
z
Hmm, I see the complexity.
I think I like the method reference the closest out of those options. Could maybe do it with a lambda, but I'm not sure what caveats that might have, like
Copy code
val (
    name = { name },// lambda of right-hand side with implicit this
    group = { group },// same name as prop
    myParameters = { parameters },// new name
    myValue = { value },
    // could maybe make it n-arity, as long as implicit this is maintained
    isUppercase = { value.isUpper() },
    groupIsNull = { group == null }
) = property
// each of these is basically just a call to property.map with a `this`
Thanks for pointing me to the issue though!