https://kotlinlang.org logo
Title
d

Danilo Herrera

02/21/2019, 6:52 PM
Is there a way to ensure a generic type is a data class?
:no_red: 2
r

Ruckus

02/21/2019, 6:56 PM
Why would you want that?
d

Danilo Herrera

02/21/2019, 6:58 PM
I was trying to create a copy of a generic value which was only meant to be a data class
r

Ruckus

02/21/2019, 7:02 PM
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

Danilo Herrera

02/21/2019, 7:07 PM
I suppose. I guess I was trying to clone a generic type, and know that data classes have the
copy
method.
d

Dominaezzz

02/21/2019, 7:10 PM
You could always make a
interface Copy<T> { fun copy(): T }
. Not sure how nicely it'll play with data classes though.
1
👍 2
r

Ruckus

02/21/2019, 7:19 PM
@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

streetsofboston

02/21/2019, 7:20 PM
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

Danilo Herrera

02/21/2019, 7:23 PM
I see. That makes sense. Ended up using this interface:
interface Cloneable<T> {
    fun clone(): T
}
which in turn makes the data classes have this implementation:
data class User(val id: String) : Cloneable<User> {
    fun clone() = copy()
}
👍🏼 1
👍 1
k

karelpeeters

02/21/2019, 8:00 PM
You can get a bit more type safety with
interface Cloneable<T: Clonable<T>>
👍🏼 3
2