0

I have a class structure like below:

abstract class AuthorizeSalesRequestDto {
    open val sequenceNumber: Int = 0
    open val currentService: String = ""
    open val amount: Int = 0
    open val taxOthers: Int = 0
    open val trainingMode: Boolean = false
}

data class CreditAuthorizeSales(
        override val currentService: String = "Credit"
) : AuthorizeSalesRequestDto() {

}

data class UnionPayAuthorizeSales(
        override val currentService: String = "UnionPay"
) : AuthorizeSalesRequestDto() {

}

I want to init the CreditAuthorizeSales and UnionPayAuthorizeSales like below:

val creditObject = CreditPayment(
        sequenceNumber = 1,
        amount = 100,
        taxOthers = 10,
        trainingMode = true
)

I create class structure because future will be more data class like CreditAuthorizeSales for different service. But I can't figure out a way to make a constructor like above. Can somebody please help me with the syntax or change the class structure? Thanks in advace!!!

Note: Enviroment

  • Kotlin v1.4.3
Dattq2303
  • 302
  • 2
  • 13
  • 1
    Are you sure you want to do this? None of the properties in `AuthorizeSalesRequestDto` except `currentService` will be used to generate the `equals`, `hashCode`, and other useful methods in `CreditAuthorizeSales`. And since when is there a Kotlin 3.5? The latest version is 1.5.x as far as I know. Anyway, it seems like you are overusing inheritance. Do you _really_ need `CreditAuthorizeSales` and `UnionPayAuthorizeSales`? How about just make `AuthorizeSalesRequestDto` a data class, and use a factory to produce objects with different `currentService`? – Sweeper Aug 17 '21 at 04:51
  • @Sweeper yeah i think your idea seem better but because these class will be used also in difference module code so it is important to make these dto class to become seprate class. – Dattq2303 Aug 17 '21 at 05:04
  • @Sweeper Can you please explain more about "None of the properties in AuthorizeSalesRequestDto except currentService will be used to generate the equals, hashCode, and other useful methods in CreditAuthorizeSales" ? – Dattq2303 Aug 17 '21 at 05:21
  • 1
    You know that [data classes](https://kotlinlang.org/docs/data-classes.html) will have `equals` and `hashCode` and other useful methods automatically generated, right? The generated methods will only use the properties that you put in the primary constructor, in this case, `currentService`, and not any of the properties in the superclass. – Sweeper Aug 17 '21 at 05:23
  • @Sweeper I know that but i thought that the primary constructor of CreditAuthorizeSales will call constructor of AuthorizeSalesRequestDto and it still going to be generated? – Dattq2303 Aug 17 '21 at 05:26

0 Answers0