Search code examples
kotlinconstructorsuper

Call SuperConstructor from secondary constructor


I have the class Circle which extends CanvasElement. I want to be able to create a circle just by giving a radius AND by initializing with the total set of values. At the moment, my code looks clunky, setting each value from the super class one by one. How can I just call the super constructs with all values (posX, posY, etc. passed into the constructor call?

class Circle(var radius : Double = 0.0) : CanvasElement(){
constructor(posX : Double,
        posY : Double,
        radius : Double,
        fill : String,
        stroke : String) : this(radius){
    this.fill = fill
    this.stroke = stroke 

    this.posX = posX
    this.posY = posY
}

Class: CanvasElement

open class CanvasElement(
    var posX : Double = 0.0,
    var posY: Double = 0.0,
    var fill : String = "",
    var stroke : String = ""){
}

For a better understanding, I have added the java code for what I want to achieve:

Circle

public class Circle extends CanvasElement{
    private int radius;

    public Circle(int radius){
        super(0,0);
        this.radius = radius;
    }
}

CanvasElement

public class CanvasElement{
    private double posX;
    private double posY;

    public CanvasElement(double posX, double posY){
        this.posX = posX;
        this.posY = posY;
    }
}

Solution

  • Do you would like to have something like this?

    open class CanvasElement(var posX: Double , var posY: Double, var fill: String , var stroke: String)
    
    class Circle(var radius: Double = 0.0,
                 posX: Double = 0.0,
                 posY: Double = 0.0,
                 fill: String = "",
                 stroke: String = "") : CanvasElement(posX, posY, fill, stroke)
    

    IF I understood you properly you don't want CanvasElement to have deafults and you want to be able to create a Circle by defining only the radius and possibly other properties that CanvasElement has.