edwardwongtl
11/21/2018, 4:25 AMenum 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
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
?Joris PZ
11/21/2018, 6:52 AMdata 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
}
}
edwardwongtl
11/21/2018, 7:30 AMJoris PZ
11/21/2018, 7:55 AMdata 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-reflectionJoris PZ
11/21/2018, 7:55 AMedwardwongtl
11/21/2018, 7:57 AMedwardwongtl
11/21/2018, 8:23 AM