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 class Person(
val name: String,
val address: Address
)
data class Address(
val nation: Nation,
val state: String,
val street: String
)
data class Nation(
val name: String,
val code: 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.gradle
orbuild.gradle.kts
dependencies { 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" ) ) )