The kotlin in action book has a section where it r...
# getting-started
s
The kotlin in action book has a section where it recommends to make data classes immutable using val. It states that kotlin creates the toString, equals and hashCode methods that we used to implement on our own in Java and gives this as a reason why immutable data classes are recommended. I'm having a hard time understanding why it is recommended this way. What are your thoughts on this?
j
Immutability and Data Classes are two separate, awesome things. Data Classes make your life easier by ensuring that
toString
,
equals
and
hashCode
are always up-to-date. Add a new field? No need to remember to add it to
equals
or the other functions, it happen automatically!
Immutability makes code easier to understand and follow a lot of the times. Having guarantees that a field will stay the same are really nice for the user of an object and can help prevent bugs. e.g. no one will accidentally update the
created
timestamp on a db object if it's immutable
a
I think the relationship is that immutability is easy with the
copy()
method you get from data classes. You shouldn't need to make the properties of your data classes var, when you could just do
val newItem = originalItem.copy(changedProperty = 5)
k
If you put an object in a
HashMap
and then you mutate a property which causes the hashcode to change the map basically breaks, so you're not allowed to do that.
Instead of having to think "I can only mutate this of it's not part of any collection" it's easier to just never mutate it.
c
Immutability improves safety and also performance. While I was doing my fsm project I initially had a StateMachineDefinition and StateMachineInstance that referred to the definition. The definition had mutable collections so that your code could create the definition with multiple calls. I also did performance testing. Then I split the definition into a StateMachineBuilder with mutiple collections for creating the definition and the build function create the definition with all immutable collections. That change provided a 10% improvement in the execution time of the core statemachine that was using the collections to determine what to do.