Hello, Suppose I have two data classes DataClass1...
# getting-started
u
Hello, Suppose I have two data classes DataClass1 and dataClass2. DataClass2 is identical to dataClass1 except that it lacks the first variable.
Copy code
data class DataClass1(
    val entry0: Any,
    val entry1: Any,
...
    val entryN: Any
)

data class DataClass2(

    val entry1: Any,
...
    val entryN: Any
)
Suppose I have dc1 as an instance of dataClass1 and want to obtain the corresponding dataClass2. version (i.e. "remove" entry0). I know that for a simple case, I could just do
Copy code
dc2 = DataClass2(
val entry1 = dc1.entry1,
val entry2 = dc1.entry2
)
But is there a way to this for the case where the number of entries is unknown?
y
A rather simple way would be to define DataClass1 to be that first val and then an instance of DataClass2. Otherwise, reflection might be your friend here, perhaps matching the properties of DataClass1 by name to the parameters of DataClass2's primary constructor
p
I'd suggest trying to understand why these data classes are so similar. Is this design fine in the first place?
👍 1
a
https://kopyk.at/ might be helpful for you
u
@Piotr Krzemiński because one class is automatically generated by a package that I do not want to alter, and another package needs the same class with the first entry (an index).
👍 1
@Adam S I'd have thought that should be feasible without a plugin though...
a
I don't think it's a problem that comes up often. I guess you're looking similar to duck typing? Is there another language where what you want is easier? That might help make it easier to suggest alternatives.
u
In Python you would just remove the first entry of a dictionary (I guess).
t
I had to dig a bit, but I once bookmarked a medium article that fits perfectly: https://nwillc.medium.com/kotlin-data-class-inheritance-by-delegation-2ad3fe6f9bd7 In essence:
Copy code
fun test() {
    val person = Person("John", "Doe", UUID.randomUUID())
    val infoFromPerson = person.info
    
    val personInfo = PersonInfo("John", "Doe")    
    val personFromInfo = Person(personInfo, UUID.randomUUID())
}

interface PersonDefinition {
    val firstName: String
    val lastName: String
}

// convenience wrapper
fun Person(firstName: String, lastName: String, id: UUID) = Person(PersonInfo(firstName, lastName), id)

data class Person(
    val info: PersonInfo,
    val id: UUID
) : PersonDefinition by info

data class PersonInfo(
    override val firstName: String,
    override val lastName: String,
) : PersonDefinition
u
@Tobias Suchalla thanks! The things is I can't modify DataClass1... only DataClass2. In the example from the post, they rewrite the Person class. That's not an option for me.