Re:Data Classes for Java
by tantalor on Wednesday November 01, 2017 @08:08PM
(#15606712)
AutoValue with Builders is nice:
https://github.com/google/auto/blob/master/value/userguide/b...
[ Parent
| on HN ]
Not that nice compared to kotlin:
data class Animal(dog: String, numberOfLegs: Int)
val dog = Animal(
name = "dog",
numberOfLegs = 4
)
The amount of boilerplate for AutoValue builders is so ridiculous that most people use IDE plugins to generate it.In clojure I'd write this, if I actually needed a class for type dispatch or interface implementation for some reason.
(s/defrecord Animal
[name :- String
number-of-legs :- Integer])
(def dog (map->Animal
{:name "dog"
:number-of-legs 4}))
The nice thing is that I could also skip the defrecord if I just want enforcement of the shape of the data by making a similar defschema and then I'd just use plain maps.
Re:Data Classes for Java
by billrobertson42 on Saturday November 04, 2017 @02:49PM
(#15626346)
I mucked around with records a lot early on while learning Clojure, and I'm not really sure when I stopped and just started using maps. Now it's second nature and I'd only consider using a record if there was some overriding performance concern.
data class Animal(dog: String, numberOfLegs: Int)
and Animal dog = Animal.builder()
.setName("dog")
.setNumberOfLegs(4)
.build();
are very different. In this case the builder pattern is more powerful as it lets you pass around builders that haven't been "built" yet. Kind of like currying.True, but the constructor method is checked/validated at compile time vs. run time with the builder pattern. Not quite the same as your example, but Kotlin does have good syntax for copying data classes while only changing a single field - this could be used similar to your currying usage.
https://kotlinlang.org/docs/reference/data-classes.html#copy...
Here's that kotlin copy syntax
val cat = dog.copy(name = "cat")Nope, we just add @AutoBuilder
A code generator for your code generator.
Agreed. The amount of boilerplate is reduced significantly in Kotlin. it has builder methods also which help greatly with data classes like apply(), with() and let() for us it became language of choice for backend for these reasons
Re:Data Classes for Java
by jimmaswell on Wednesday November 01, 2017 @09:49PM
(#15607193)
Very similar in C#:
var dog = new Animal(){ name="dog", numberOfLegs=4 };
I use it all the time.
Re:Data Classes for Java
by bunderbunder on Wednesday November 01, 2017 @10:02PM
(#15607234)
The big difference there would be, in the C# example you've still got to write a bunch more boilerplate for Equals(), GetHashCode() and ToString(). Kotlin's data classes give you those three for free.
now in... clojure? We usually don't use dynamic dispatch, but if you wanted to explicitly have an animal-ey map with a name and number of legs, it's:
(def dog #:animal{:name "dog" :number-of-legs 4})