why cant a `data class` be `open` ?
# announcements
l
why cant a
data class
be
open
?
e
even if it were open, copy will still return the original type
l
couldnt the copy function be overriden by the subclass ?
e
not currently, and even if it could, there's no self-type in Kotlin to force it to return the subtype
n
I keep meaning to do a direct comparison with python dataclasses (which do offer this feature) and see exactly what the differences are; whether python is doing something more dynamic than is possible in Kotlin, or making some kind of compromise Kotlin is not willing to make. coming from python I'd definitely miss the ability to make dataclasses open
e
both. python is dynamic so dataclasses's
.replace()
can look up the constructor of the class of the current instance, and also allows it to fail at runtime in case of post-init fields
n
Interesting
r
we had this discussion before somewhere here and it's possible to generate
.copy()
methods in subclasses, that will behave as expected there are a few problems with it (could be probably solved by compiler?) 1. subclass can do calls in super class parameters,
data class B(val a: Int, val b: Int): A(a * 2)
would make
copy()
on B instances behave wierd AF (A is just
open data class A(val a: Int)
) - not sure what good solution could be to this... anything that solves this will make subclassing behave differently than on normal classes (tho I guess you could just do "can't do calls in data class?") 2. copy would need to be overridable, ppls could break it (could be denied by compiler I guess) 3. subclasses would have multiple copies with diff params (but compiler is able to select proper one even now, and they all behave same)
e
allowing for subclassing also allows for Java subclasses, on which the Kotlin compiler can't enforce any rules…
r
Pesky Java always sticking it's dirty fingers into Kotlin...