1

I'm working with an immutable data-structure in Java and am getting mildly annoyed, by the tedious work of copying each object when I want to change the properties of them.

I know in Kotlin this can be done easily with the data-classes .copy() function. And I want to know if there is the same function in Java? Maybe over some library?

Something that would allow stuff like this:

Implementation:

fun copy(name: String = this.name, age: Int = this.age) = User(name, age)

Usage:

val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)

Thanks for your help ^^

Jakob Sachs
  • 464
  • 2
  • 15
  • Nope, there's nothing with that black magic power in java... Unfortunately :*( You have to create your helpers methods / utilities by hand, there's nothing by design that do that. – Leviand Aug 30 '18 at 10:01
  • You can also generate those, e.g. with your IDE's template generator. But do not forget to regenerate if fields change! (similar to generated `toString`, `equals`, `hashCode` etc.) ... and don't forget, that you can actually write the `data class` in Kotlin and just use it in Java... – Roland Aug 30 '18 at 11:09

0 Answers0