3 ms·
I think that case classes are roughly equivalent to Kotlin data classes for the purposes of this comparison. In particular, one of the extra features they offer
by mumblemumble 5y ago
I think that case classes are roughly equivalent to Kotlin data classes for the purposes of this comparison. In particular, one of the extra features they offer is the ability to make fields mutable. Which, in some cases, may be useful, but also means that they aren't, strictly speaking, transparent carriers of immutable data.
- valenterry 5y agoNot only that, but they offer some other features that (to my knowledge) both records and kotlin's data classes don't offer. Which is control over accessibility. E.g. when you have a "NegativeNumber" type and you need to make sure the inner value is actually negative. Then just using having a check in the constructor isn't sufficient in the existence of copy methods (like kotlin) does it.
- snuxoll 5y agoThe copy methods that Kotlin generates construct a new instance of the class with the updated fields - so any validation done in the constructor would in fact be done again.
- valenterry 5y agoYes, that's correct. But instead of catching the error at that point, you would probably rather want to disable these methods from the beginning so that someone cannot even make the mistake of using them and has to go through some custom defined method instead.
- jillesvangurp 5y agoA good rule is that constructors MUST not do work. Writing constructors in Kotlin is possible but not that common. Data classes are typically initialized with just value assignments. Having support for default values also means that it largely removes the need for having multiple constructors (which is very common in Java). If you need to do validation, there are very decent frameworks that you should use for both Java and Kotlin. We are using a thing called Konform currently. Very nice. For non negative numbers, you can use the new unsigned numeric types they added in Kotlin with the last release: https://kotlinlang.org/docs/basic-types.html#unsigned-integers https://kotlinlang.org/docs/basic-types.html#unsigned-intege...