Home > Software engineering >  Assigning abstract val a value in sealed class
Assigning abstract val a value in sealed class

Time:11-26

I've a sealed class from which a couple of abstract classes inherit from. Since there are a bunch of fields in sealed class that need to be initialized in abstract class, I'm trying to move it to the secondary constructor however secondary constructor doesn't let us declare override val fields to make the code a bit more concise. The only other way I can think of is to make the fields lateinit var but then I loose immutability.

sealed class Animal {
  abstract val object1 : SomeObject
  abstract val object2 : SomeObject2
  abstract val object3 : SomeObject3
  abstract val object4 : SomeObject4
}

abstract class GrassEaterAnimal : Animal {

   //trying to do this
   constructor(override val object1 : SomeObject, override val object2 : SomeObject2, override val object3 : SomeObject3, override val object4 : SomeObject4, func : (field1, field2) -> Foo)
}

Is there a way to make this code cleaner or any other suggestions that can help in this situation?

CodePudding user response:

You can implement/initialize properties in the primary constructor:

abstract class GrassEaterAnimal(
    override val object1: SomeObject,
    override val object2: SomeObject2,
    override val object3: SomeObject3,
    override val object4: SomeObject4,
) : Animal()
  • Related