https://github.com/johnsonlee/mutator
Mutator for Immutable Object
https://github.com/johnsonlee/mutator
Last synced: about 1 year ago
JSON representation
Mutator for Immutable Object
- Host: GitHub
- URL: https://github.com/johnsonlee/mutator
- Owner: johnsonlee
- License: apache-2.0
- Created: 2022-04-07T14:46:37.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2022-04-10T15:56:43.000Z (about 4 years ago)
- Last Synced: 2025-03-28T23:51:11.942Z (about 1 year ago)
- Language: Kotlin
- Size: 70.3 KB
- Stars: 6
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Mutator
## Why Mutator?
As the [immutable object](https://en.wikipedia.org/wiki/Immutable_object) becomes the default pattern of functional programming language, such as [Value Object](https://en.wikipedia.org/wiki/Value_object) in Java, and [Data Class](https://kotlinlang.org/docs/data-classes.html) 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:
```kotlin
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:
```kotlin
val person = Person(...)
// ...
val clone = person.copy(
address = person.address.copy(
nation = person.address.nation.copy(
code = "New Code"
)
)
)
```
## Getting Started
1. Add dependency into `build.gradle` or `build.gradle.kts`
```kotlin
dependencies {
implementation("io.johnsonlee:mutator:1.2.0")
}
```
1. Call the extension function `mutate(...)`
```kotlin
val clone = person.mutate(Person::address, Address::nation, Nation::code, "New Code")
```
The code above is equivalent to the following
```kotlin
val clone = person.copy(
address = person.address.copy(
nation = person.address.nation.copy(
code = "New Code"
)
)
)
```