Endre Deak
12/19/2022, 7:00 PMcopy
method in place?jw
12/19/2022, 7:06 PMkioba
12/19/2022, 7:45 PM// 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.