Since Kotlin 2.0.20, the `copy` method of a data c...
# getting-started
j
Since Kotlin 2.0.20, the
copy
method of a data class has the same visibility as the primary constructor. However, the library guidelines still instructs to avoid data classes in public API. I have a class really similar to a data class. I went for a basic class because I wanted all the features of a data class, except my constructor is internal and I didn't want to expose a
copy
method. Can I swap it for a data class? I'm aware it will expose
componentX
methods but I already provide them (code in thread)
Copy code
public class ConstraintViolation internal constructor(public val message: String, public val path: Path) {
    public operator fun component1(): String = message
    public operator fun component2(): Path = path

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other == null || this::class != other::class) return false

        other as ConstraintViolation

        if (message != other.message) return false
        return path == other.path
    }

    override fun hashCode(): Int {
        var result = message.hashCode()
        result = 31 * result + path.hashCode()
        return result
    }

    override fun toString(): String = "ConstraintViolation(message='$message', path=$path)"
}
c
For “data” classes that are part of an API I’ve been using Poko to allow using a regular class with Poko adding the equals, toString, hashCode, thereby providing a stable ABI.
j
This could be an option for other classes, thanks! But for a class with a private constructor and defined
componentX
methods, can't I just use data classes?
b
We still don't recommend to use data classes in public API. Data class is a convenience/shortcut feature, and should be percieved as such. In your library API, you better to have full control over what you expose. Convenience features generally don't provide full control Examples: one day we might want to generate yet another functions inside data classes. Or we might deprecate
componentX
j
Alright, that's good to know, thanks 🙂
I will probably go with Poko like @Chris Lee have suggested
👍 1