https://kotlinlang.org logo
#announcements
Title
# announcements
w

Wesley Acheson

12/09/2019, 11:48 AM
Sorry new to all of this but is there a way to wrap and extend a data class. Say if I had a data class
Summary
and I wanted to create a data class
SummaryCalculation
that had all the fields of Summary but had new field also.
Copy code
data class Summary(val aProperty:String, val items:List<BillableItem>)

//This I don't know
data class BillingSummary(initialSummary:Summary, totalItemsBilled:Long):Summary
It doesn't actually need to share an equals/hashcode, just expose the same api. I'm more or less trying to create an envelope that holds addition properties. that can be created from the initial object.
d

diesieben07

12/09/2019, 11:50 AM
You can share a common interface between the two:
Copy code
interface Summary {
    val aProperty: String
}

data class SummaryData(override val aProperty: String) : Summary

data class BillingSummary(val initialSummary: Summary, val totalItemsBilled: Long) : Summary by initialSummary
w

Wesley Acheson

12/09/2019, 11:53 AM
Thank you I think that should work. Not familiar with the
by initalSummary
syntax.
d

diesieben07

12/09/2019, 11:55 AM
It implements the interface by delegating all functions / properties to the implementation you give it.
m

Matteo Mirk

12/18/2019, 9:05 AM
@wes to understand that syntax read about delegation: https://kotlinlang.org/docs/tutorials/kotlin-for-py/inheritance.html#delegation
w

Wesley Acheson

12/18/2019, 3:25 PM
@Matteo Mirk Thanks
👍 1
2 Views