Wouldn’t it be great if I could easily create an i...
# language-proposals
m
Wouldn’t it be great if I could easily create an immutable version of an instance of a data class with mutable properties? I wonder how that could be done. It’s not easy, but it would be really cool if I could define something like a
MutablePerson
, and it would then automatically have a method
toPerson(): Person
.
Ok, generating the Person class would be too much to ask from the compiler. How about something like this:
Copy code
data class MutablePerson(var name: String? = null, var age: Int? = null) {
    immutable derived data class Person(val name: String, val age: Int)
}

val p: Person = buildPerson {
    // receiver is a new MutablePerson instance
    name = "Fred"
    age = 42 
}
Maybe it would also make sense to turn it around - define the immutable data class and have a mutable version generated.
j
interface MyPair<A,B>{val a:A;val b:B};class MyPair2(override var a:A,override var b:B):MyPair{};
p
The KEEP for value classes talks about a possible future enhanced syntax for immutable classes to make their modification easier https://github.com/Kotlin/KEEP/blob/master/notes/value-classes.md#updating-immutable-classes
Sort of the inverse of what you're proposing - define the immutable class yourself, and just make it easier to mutate
👍 1
n
I actually wanted to make a compiler plugin to do exactly this.
👍 1
n
I'm currently experimenting with something similar: https://discuss.kotlinlang.org/t/state-handling-using-immutable-objects/24423 It is a very complex topic...