Inheritance – How to use multiple parent configuration functions with VAL in subclasses

Suppose I have a class Parent, which has four fields A, B, C, and D, so that C and D are optionally passed or initialized using the default implementation:

open class Parent(val a: A, val b: B, val c: C, val d: D) {
constructor(a: A, b: B , c: C): this(a, b, c, DImpl()){}
constructor(a: A, b: B): this(a, b, CImpl(), DImpl()){ }
}

I need to extend this class and add another field to the subclass:

class Child: Parent {
val e: E // How do I initialize this?
)

Passing val to the auxiliary constructor does not work, nor does it use the init () block.

Passing val to the main constructor works, but I lose the delegation to the auxiliary constructor in the Parent class-I need to use all the parent constructors and all the parameters, or copy the auxiliary constructor, leaking the implementation details to the Child class.

This should be simple, what am I missing here?

If you really need to use auxiliary constructors, and you cannot use the default values ​​suggested by @Ingo Kegel, then The e field can be initialized by assigning the parameter value to the attribute, just like doing this in Java:

class Child: Parent {
val e: E

constructor(a: A, b: B, c: C, d: D, e: E): super(a, b, c, d) {
this .e = e
}
}

Suppose I have a class Parent, which has four fields A, B, C and D, like this C and D are optionally passed or initialized using the default implementation:

open class Parent(val a: A, val b: B, val c: C, val d: D) {
constructor(a: A, b: B, c: C): this(a, b, c, DImpl()){}
constructor(a: A, b: B): this(a, b, CImpl(), DImpl()){}
}

I need to extend this class and add another field to the subclass:

< p>

class Child: Parent {
val e: E // How do I initialize this?
}

Passing val to the auxiliary constructor does not Works and doesn’t use the init () block.

Passing val to the main constructor works, but I lose the delegation to the auxiliary constructor in the Parent class-I need to use all the parent constructors And all the parameters, or copy the auxiliary constructor, leak the implementation details to the Child class.

This should be very simple, what am I missing here?

If you really need to use an auxiliary constructor, and you cannot use the default value suggested by @Ingo Kegel, you can initialize the e field by assigning the parameter value to the attribute , Just like doing this in Java:

class Child: Parent {
val e: E

constructor (a: A, b: B, c: C, d: D, e: E): super(a, b, c, d) {
this.e = e
}
}

Leave a Comment

Your email address will not be published.