Home > Back-end >  How to create a new object from data class
How to create a new object from data class

Time:03-16

I have a data class which extends another abstract class.

data class Savings(
  val amount: BigDecimal? = null
) : Account()

abstract class Account(
  val accountNumber: BigDecimal? = null
)

val saving: Savings = Savings(amount = BigDecimal.ONE)

How can I set the value for accountNumber property as that is not available in constructor. What other way I can set the value of the field?

CodePudding user response:

You can make the property open in the superclass so you can override it in the data class constructor:

data class Savings(
  val amount: BigDecimal? = null,
  override val accountNumber: BigDecimal?
) : Account()

abstract class Account(
  open val accountNumber: BigDecimal? = null
)
  • Related