3 ms·
Not 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
by valenterry 6y ago
Not 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 6y 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 6y 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 6y 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...