A question related to reflection and `data class`’...
# announcements
e
A question related to reflection and `data class`’s copy method. Currently I am have something like this
Copy code
enum class GeneralModifier {
    Less, Normal
}

data class Latte(
    val ice: GeneralModifier = GeneralModifier.Normal,
    val milk: GeneralModifier = GeneralModifier.Normal
) : Coffee()
And the selection input is
Pair<String, Enum<GeneralModifier>>
, where the first one is the field name, e.g. “ice” So I do
Copy code
tem.copy(
  ice = if (field == "ice") GeneralModifier.values().first { it == option } else item.ice,
  milk = if (field == "milk") GeneralModifier.values().first { it == option } else item.milk
)
Is there a easier way to do the
copy
?
j
I would do something like
Copy code
data class Latte(
    val ice: GeneralModifier = GeneralModifier.Normal,
    val milk: GeneralModifier = GeneralModifier.Normal
) : Coffee() {
    
    fun modify(input: Pair<String, GeneralModifier>) =
        when(input.first) {
            "ice" -> this.copy(ice = input.second)
            "milk" -> this.copy(milk = input.second)
            else -> this
        }
}
e
Then I have to repeat the function for every similar class..seems not much better
j
Maybe something like this is what you are looking for?
Copy code
data class Person(val name: String, val age: Int)
    val person = Person("Jane", 23)
    val copy = person::class.memberFunctions.first { it.name == "copy" }
    val instanceParam = copy.instanceParameter!!
    val ageParam = copy.parameters.first { it.name == "age" }
    val result = copy.callBy(mapOf(instanceParam to person, ageParam to 18))
    println(result)
Taken from https://stackoverflow.com/questions/49511098/call-data-class-copy-via-reflection
1
Wouldn't be too hard to adapt this to your case
e
This seems to be a more general solution, I’ll give it a try
The copy via reflection works like a charm! Thanks a lot