Is there a way to ensure a generic type is a data ...
# announcements
d
Is there a way to ensure a generic type is a data class?
no red 2
I was trying to create a copy of a generic value which was only meant to be a data class
r
only meant to be a data class
Why? what's significant about a data class? Ultimately they're just normal classes with some functions generated for you, and even those functions can be overridden, so being a data class doesn't really get you anything.
d
I suppose. I guess I was trying to clone a generic type, and know that data classes have the
copy
method.
d
You could always make a
interface Copy<T> { fun copy(): T }
. Not sure how nicely it'll play with data classes though.
👍 2
s
Problem with the
interface Copy
, the
copy
function of a data class has an unknown signature, except for its name and return type
d
I see. That makes sense. Ended up using this interface:
Copy code
interface Cloneable<T> {
    fun clone(): T
}
which in turn makes the data classes have this implementation:
Copy code
data class User(val id: String) : Cloneable<User> {
    fun clone() = copy()
}
👍🏼 1
k
You can get a bit more type safety with
interface Cloneable<T: Clonable<T>>
👍🏼 3
2