here's an interesting topic: mutable data classes ...
# java-to-kotlin-refactoring
p
here's an interesting topic: mutable data classes 🙂 Duncan and Nat claim that it's unsafe with respect to
equals
and
hashCode
, and it's actually great point - I've never looked at it this way, maybe because I create deeply immutable data classes (unless I refactor some JavaBeans-style code, I leave `var`s temporarily) IMO IntelliJ should add a warning/inspection, like it's done for e.g. using
Optional
for class fields. The goal still being able to create a concise, kotlinic version of a JavaBean, but not pretending that it's fine 🙂 .WDYT?
d
Interestingly I’m involved in a (Python) project at the moment where we want to have mutable objects cache and update their hashcodes in order to implement memoization. I’m not really clear how this would work and have the ability to look up a mutable object by its hash, unless the storage is notified of mutations and updates its lookup accordingly.
I think on the whole I stand by my view that data classes have been immutable, and maybe a warning would be a good idea. Taking it further though, should the warning extend to non-mutable references to mutable objects as properties of data classes?
👍 1
p
Shallow/deep mutability, good point! I wouldn't mind getting a warning about using
java.util.Date
as a
val
, these things can happen to even experienced and diligent coders. There's a question how to implement it correctly so that it works for a bunch of edge cases, but in terms of what would be useful - it makes sense.
I'm thinking about gathering such cases regarding data classes, starting writing a KEEP , and let's see what happens. These could be individual feature requests, but it's better to take a look at the big picture first. The goal would be to still leave the pragmatic side of data classes and generally Kotlin in terms of mutability, but have the utilities at hand to further refine it. Short-term: opt in to have better safety, long-term: safety being the default and ability to opt out to get Java-like behavior. The ideas being any subset of: compiler and IDE warnings, modifiers enabling the compiler to fail on the lack of desired immutability, IDE refactorings towards immutability, and more.
n
It looks like a future version of Kotlin will support value classes, as distinct from data classes. A value class will be immutable and have value semantics. https://github.com/Kotlin/KEEP/blob/master/notes/value-classes.md
👍 1
But the details are still in flux