As the immutable object becomes the default pattern of functional programming language, such as Value Object in Java, and Data Class in Kotlin, even the immutable pattern has a lot of advantages, modifying properties of deeply nested immutable objects is still not very convenient, for example:
data classPerson(
valname:String,
valaddress:Address
)
data classAddress(
valnation:Nation,
valstate:String,
valstreet:String
)
data classNation(
valname:String,
valcode:String
)If we want to modify the Person.address.nation.code, we have to write code like this:
val person =Person(...)
// ...val clone = person.copy(
address = person.address.copy(
nation = person.address.nation.copy(
code ="New Code"
) )
)Add dependency into
build.gradleorbuild.gradle.ktsdependencies { implementation("io.johnsonlee:mutator:1.2.0") }Call the extension function
mutate(...)val clone = person.mutate(Person::address, Address::nation, Nation::code, "New Code")
The code above is equivalent to the following
val clone = person.copy( address = person.address.copy( nation = person.address.nation.copy( code ="New Code" ) ) )