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
r
Why would you want that?
d
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
1
r
@Danilo Herrera Data classes can't do that, as their generated
copy
functions all have different signatures (unfortunately Kotlin doesn't consider a function with all default parameters the same as a function with no parameters), so even though you can cal
copy()
on all of them, they get compiled down to different (unrelated) function calls.
s
Problem with the
interface Copy
, the
copy
function of a data class has an unknown signature, except for its name and return type
1
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
👍🏼 1
k
You can get a bit more type safety with
interface Cloneable<T: Clonable<T>>
👍🏼 3
2