Issue
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?
Solution
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()
Answered By - broot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.