youngDev
youngDev

Reputation: 339

kotlin: set default values for a parent class

I am trying to achieve the most concise combination for a parent and a child class in Kotlin.

This is like my classes look like.

sealed class Parent {
 open val attribute : String = "initial value"
}

data class Child (
  override val attribute: String
) : Parent ()

I would like to have the attribute value set as "initial value" if the constructor Child() is empty.

And I would like to have an opportunity to set the attribute value of a Child-object through the constructor if I want it to be something else (not equal to "initial value")

Is it possible in Kotlin?

Upvotes: 2

Views: 3277

Answers (1)

Roland
Roland

Reputation: 23242

Here is a way to have your subclass reuse the initial value from the superclass (which was a valid answer until the data class Child appeared):

sealed class Parent(val attribute : String = "initial value")

class Child : Parent {
  constructor() : super()
  constructor(attribute: String) : super(attribute)
}

This way cou can now call either your default constructor of the Child which will result in "initial value" or pass an appropriate attribute instead. However this will not work with a data class Child as you need to have a primary constructor there.

The following will set the attribute to "initial value" when calling the "default" Child-constructor:

sealed class Parent {
  open val attribute : String = "initial value"
}

data class Child (override val attribute: String) : Parent() {
  constructor() : this("initial value")
}

In fact it's rather a secondary constructor. As you can only call super constructors if you do not have a primary in the subclass, your remaining options are rather small. You may want to redesign your class hierarchy or just hold some constant somewhere.

Upvotes: 1

Related Questions