Is there anyway for me to call the `copy` functio...
# getting-started
j
Is there anyway for me to call the
copy
function on a generic type? I would like to change the generic type of
T
to make sure that it's a
data class
. Or is this just impossible?
Copy code
fun <T: Any> doCopy(dataObject: T): T {
    return dataObject.copy()
}
a
the run-time has type erasure - but if you make the function inline, and reify the type, you get access to it, as you’ll only be able to call doCopy in a way such that Kotlin knows that T is compile time
I might have answered the wrong question just then - I suppose what you need to know here, is what the type of an arbitrary data class is 🙂
j
atleast this is still not working
Copy code
inline fun <reified T: Any> doCopy(dataObject: T): T {
    return dataObject.copy()
}
h
It is impossible. The compiler generates the copy method, there is no
Copyable
interface or similar.
👍 1
j
That's what I expected, but was just hoping for some Kotlin magic here 😛
h
If you want to copy your classes, you could create the Copyable interface:
Copy code
interface Copyable<T> {
  fun doCopy(): T
}

data class Foo(val s: String): Copyable<Foo> {
  override fun doCopy() = copy()
}
🙌 1
454 Views