is there any effort to generate DSL for the data c...
# language-proposals
e
is there any effort to generate DSL for the data class
copy
method?
Copy code
data class Foo(val bar: String)

val foo = Foo("bar")
foo.copy(bar = "bar1") // current

// could be this:
foo.copy {
   bar = "bar1"
}
e
What's the use-case?
r
You could write
Copy code
foo.copy(
   bar = "bar1"
)
What do the curly braces gain you?
e
thanks! No specific use-case, just wondering if this could be generated in a more DSL-like style.
e
Okay.. There's really not much of a difference.. 🙂 and sometimes it's nice that there's a single way of doing things (easy for people to recognize what's going on)
a
@Endre Deak I’m the author of KopyKat, and I’m happy to add new features that would help in your use case 🙂
j
@Emil Kantis there is a big difference, though. Binary compatibility. The current copy has all properties as parameters, which means its signature changes every time the properties of the class change
e
And DSL would maintain binary compatibility?
j
Yes, because the signature would probably be something like:
fun copy(block: TheClassBuilder.() -> Unit)
Setting properties of
TheClassBuilder
would only call setters that are actually necessary, so if a property is added, it won't break anything
e
Gotcha, not fully aware of how binary compatibility works but that makes sense. Thanks for explaining. 🙂
Do you see any advantages of the non-DSL version? Was it chosen simply because it's most straightforward to implement or could there be good reasons a DSL was not chosen?
j
I honestly don't know. If you want to know more about data classes and binary compatibility, you can read Jake Wharton's article about it: https://jakewharton.com/public-api-challenges-in-kotlin/
👍 2
It could have been overlooked by the Kotlin team, but I doubt it. Probably they considered other things more important. For example, the DSL version requires the generation of a mutable builder, which adds classes and methods, which could be a problem for Android's "method count".
a
Love this idea! DSL would also allow having local variables scoped inside the lambda. And it would be less verbose in some cases.
some.copy(count = some.count + 1)
vs
some.copy { count += 1 }
a
that is exactly what KopyKat does, albeit using a plug-in instead of being built in the language
it gives you a “mutable view” that you can modify in the block, and at the end a new copy is created
a
Yeah, I'm aware of KopyKat - great library! Would love to have it as a language feature, though. 🙃
e
j
I remember reading and debating a lot about this when it was first published. Now it just occurred to me that a "copyable property" is a funny name, because the property in question is literally the only thing that is NOT copied when we use the feature 😆 (we make a copy of the object, a copy of the value of all other properties, but not a copy of the copyable property that we're modifying)
141 Views