3 ms·
Honestly I don't understand point of data classes. Why was it introduced into language? The only time when I'm implementing equals/hashCode is when I'm going to
by vbezhenar 9y ago
Honestly I don't understand point of data classes. Why was it introduced into language? The only time when I'm implementing equals/hashCode is when I'm going to use this class as a hash key and it's quite a rare situation. Why introduce a keyword just for that? Am I missing something? I'm using Kotlin and I'm just using classes without data modifier, they work just fine.
- on_and_off 9y ago1- automatic equals & hashcode is awesome. With data classes, you no longer need AutoValue. 2- it also adds toString and destructuring functions. for the data layer, 'data' classes are awesome IMO.
- tomjen3 9y agoIt may just be me, but I find that sooner or later I need to debug or print something to the console and having a reasonably to string method already implemented means I don't have to be annoyed I forgot it and go back.
- cle 9y agoIt's really easy to throw a data obj into a map/set and forget to check that it correctly implements equals+hashCode. Or add a field to a data class and forget to update equals/hashCode. Or log a list/set/map without realizing that the toString is just going to print some useless hash code. Data classes handle all of that for you, automatically.
- wtetzner 9y agoOne important reason for equals/hashCode on data objects is that you can put them into sets, and have them uniqued correctly. Also, do you really never need to call .equals on data objects?
- krzyk 9y agoequals/hashCode is useful in tests also when you want the check that the returned object is what you expect, instead of doing field by field comparison: Foo foo = bar.foo(); Assertions.assertThat(foo).equalTo(new Foo(1, 2, 3)); instead of: Foo foo = bar.foo(); Assertions.assertThat(foo.getFirst()).equalTo(1); Assertions.assertThat(foo.getSecond()).equalTo(2); Assertions.assertThat(foo.getThird()).equalTo(3);