0

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?

2

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

So this needs to be done for all fields. Now I wonder if there is any point in creating abstract class with so much code duplication in Kotlin
I guess that would be true if the only reason you want to use an abstract class is to reduce the amount of code. It’s a shortcoming with data classes. It might be easier to define a standard class and use IDE features to generate equals and hashcode for you. Data classes are meant for simple data containers so it is not often that it makes sense for it to be a subclass of something.

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.