Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How exactly are they better from Kotlin's data classes?

Aside from the fact Java only released non-preview support for records one month ago, they:

  - Don't support inheritance
  - Can't be mutable
  - Don't have a copy method
While Java records are nice, Kotlin data classes are strictly more capable than Java records.


FWIW I think that whether someone wants to use mutable objects or swears by immutability should be their choice, especially for interoperability with legacy code. It can be much easier to 'just go with the flow and be careful' in a legacy code base vs trying to have a clear separation of where immutability has been introduced already and where we still don't use it. Not everything is green field (in fact most stuff isn't) and not every company gives you enough time to always Do The Right Thing (TM).

Copying objects is a well known need and there are countless libraries that try to help you with it. All with their own problems, notably runtime errors vs. compile time safety or pervasive use of reflection.


Why would you need a copy method for an immutable record?


When applying events, for instance. In F#, you could do:

  match msg with

  | IncreaseCounter cnt ->
   { model with Count = model.Count + cnt }

  | DecreaseCounter cnt ->
   { model with Count = model.Count - cnt }

  | ResetCounter ->
   { model with Count = 0 }

  | ChangeRubric name ->
   { model with Rubric = name, Count = 0 }
The "with" says: copy the original record by value, but change these fields. For completeness' sake: F# also has implicit returns, so the bit between brackets is the function's return value.


Python's dataclasses have a "make a copy with these fields changed" function that's rippingly useful for immutable records.


How would inheritance, mutability and an arbitrary, presumably wrong and misguided "copy method" be a feature?


Why do you think copy methods are "presumably wrong and misguided"?

For the rest, I agree that in 99% of the cases inheritance and mutability are not needed if you're using greenfield Kotlin libraries. But they are unfortunately often necessary in the Java world.

Mutable data classes are especially quite useful for reducing boilerplate when creating classes that implement the Fluent Builder pattern, which is unfortunately quite necessary if you don't have a copy method...


Copy methods are in the works, and Java's pattern matching will be better than Kotlin's.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: