Is there any way to change the visibility modifier of a copy method or disable its creation somehow? For instance, I would like to check invariants before creating a data class but the copy method might allow invalid instances to be created by copying the original object and changing its attributes.
seems like it’s not really a data class if you want to do this kind of validity logic inside of it or disable the copy method. Just make a normal class instead. If there’s some data class-like things you still want, you can implement them yourself (like the componentN() stuff)
Don’t forget that you can put validation checks in an init { } block inside the data class; that’ll be called whenever an instance is created, whether by calling its constructor directly, or via the copy() method.
Sorry to revive this thread, but since it came up in search results, I thought it’d be good to have some updated info here:
Kotlin is changing to have the visibility of copy in data classes match the visibility of their constructors. You can proactively migrate to this behavior with an annotation (@ConsistentCopyVisibility), or with a compiler flag (-Xconsistent-data-class-copy-visibility).