Data class copy visibility modifier

Hey!

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.

Checking the docs I didn’t find a way of doing it: https://kotlinlang.org/docs/reference/data-classes.html#copying

Thanks in advance.

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)

1 Like

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.

4 Likes

There is a 3rd party compiler plugin that removes copy method. I’ve never used it so I don’t know if there are any issues.

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).

See also ConsistentCopyVisibility - Kotlin Programming Language

4 Likes