4

Hi there I have gone thru the kotlin documentation and haven't found anything. What I want to do is have a generic thar must be a data class, something like

data class MyData(val pop1:Long,val pop2:String,...)

fun class MyGenericClass<T : isDataClass>(o : T){
    // This is the important part
    fun useCopy(value : Long) = t.copy(pop1 = value)
}

What I really need to achieve is to be able to use the copy function of data classes in a generic way(pop1 will always be a member of my data classes)

Thanks in advance

3
  • 2
    And what if the class doesn't have a pop1 member? My suggestion would be to define an interface, and then have your (data) classes inherit from that. Commented Nov 12, 2017 at 19:00
  • thats how I have it now, but the problem is the copy method having a method copy(pop1:Long) in the interface does not use the data class one Commented Nov 12, 2017 at 19:23
  • 1
    You could just have a sealed class or an interface and then use reflection with named arguments, although it probably would make sense to rethink your problem. This is an unusual use case. Commented Nov 12, 2017 at 19:29

1 Answer 1

3

You should consider using an interface for that particular problem. Just delegate to the data class copy in the implementation.

data class MyData(val pop1: Long, val pop2: String) : Pop1Data {
    override fun copy(pop1: Long) {
        copy(pop1 = pop)
    }
}

interface Pop1Data {
    fun copy(pop1: Long)
}

class MyGenericClass<T : Pop1Data>(private val o: T) {
    // This is the important part
    fun useCopy(value: Long) = o.copy(value)
}
Sign up to request clarification or add additional context in comments.

2 Comments

And how about the scenario when I have multiple and variant properties of some data classes? Is there a way to handle this scenario?
I haven't check this solution yet for my scenario, but I think it would be possible to pass into generic copy() method a whole interface instead of just property and due inheritance convert the actual argument to the specific type, e.g. override fun copy(obj: PopData) { copy(param1 = (obj as Pop1Data).pop1, isCompleted = (obj as Pop1Data).pop2) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.