is there a way to assume from a generic that it's ...
# language-proposals
e
is there a way to assume from a generic that it's a data class type therefore it has the
copy
method in place?
j
No, but even if you could the signature of the function is unique to every type so you can't really abstract over it anyway
👍 2
k
agree with the missing signature comment. If you are interested in a way to allow generic copy you could use `receiver`/`context receiver` to provide copy mechanism to type arguments.
Copy code
// data classes
data class A(val integer: Int)
data class B(val string: String)

// rule to be able to copy the type argument
fun interface GenericCopy<T>{
    fun T.copy(): T
}

// copy functions
val Acopy = GenericCopy<A> { copy(integer = 42) }
val Bcopy = GenericCopy<B> { copy(string = "42") }

// generic function with receiver 
fun <T> GenericCopy<T>.genericCopy(argument: T) : T = argument.copy()

// future generic function with context receiver
context(GenericCopy<T>)
fun <T> genericCopy(argument: T) : T = argument.copy()

// calling
fun main() {
    with(Acopy) {
        print(genericCopy(A(1)))  // A(integer=42)
    }

    with(Bcopy) {
        print(genericCopy(B("1"))) // B(string=42)
    }
}
in the above
genericCopy
function has a type argument
T
but the function can only be called in a scope of
GenericCopy
instance for
T
. if your generic function has an argument, the specific cases could be implemented for each of the different data class types.
👍 2