Reputation: 7696
I have class B
with to parameters x
and y
extended from class A
with parameter x
which is optional (all parmaters are non-null) how can I define B
in a way that it would be optional and it would use the optional value in constructor of A
val y = 0
val b = if (y == 0) B(y) else B(y, 0)
class B(y: Int, x: Int = 238) : A(x)
open class A(x: Int = 238)
here I have set the default value for x
in constructor of B
is there any way to achieve this without having to set default value in B
Upvotes: 2
Views: 1239
Reputation: 2087
In your situation, something like this maybe help you!
val y = 0
val b = if (y == 0) B(y) else B(y, 0)
class B(y: Int, x: Int) : A() {
constructor(y: Int) : this(y, if (y == 0) 238 else 0)
}
open class A(x: Int = 238)
Upvotes: 0
Reputation: 4841
You can achieve this with secondary constructors.
class B : A {
constructor(y: Int): super()
constructor(y: Int, x: Int): super(x)
}
For more information see Kotlin Docs.
Edit:
As @PietroMartinelli mentions the secondary constructors would not work if you need primary constructor. If the derived class has a primary constructor, the base class can (and must) be initialized right there, using the parameters of the primary constructor.
Upvotes: 5
Reputation: 1906
The approach proposed in the @Januson's answer is very nice and clean when you does not neet/would define a primary constructor in the B
subclass. If you try to do so, you get compiler errors, because auxiliary constructors must call primary constructor and can't call superclass constructors directly.
If you B
subclass need to define a primary constructor, you can approach the problem defining the default value as a constant in A
's companion object and use it in both A
's and B
's primary constructors, as follows:
open class A(val x: Int = DefaultX) {
companion object {
val DefaultX:Int = 238;
}
}
class B(y: Int, x: Int = DefaultX) : A(x)
This way you define the equivalent of a Java static final
variable, scoped to A
.
You should refer to the superclass' A.DefaultX
constant in the B
subclass, but you don't need duplicate its value in both class A
and class B
...
Upvotes: 3