从二级构造函数调用 SuperConstructor

Call SuperConstructor from secondary constructor

我有扩展 CanvasElement 的 class Circle。 我希望能够通过给出半径并通过使用总值集进行初始化来创建一个圆。 目前,我的代码看起来很笨拙,一个一个地设置 super class 中的每个值。我怎样才能用所有值(posX、posY 等传递到构造函数调用中)来调用超级构造?

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:画布元素

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

为了更好地理解,我添加了 java 代码来实现我想要实现的目标:

圆形

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;
    }
}

为什么不像在 CanvasElement 中那样使用默认值?:

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

此声明将允许传递任意数量的参数:

Circle() // Circle(radius = 0.0) + CanvasElement(0.0, 0.0, "", "")
Circle(10.0) // Circle(radius = 10.0) + CanvasElement(0.0, 0.0, "", "")
Circle(10.0, 1.0, 2.0, "red", "black") // Circle(radius = 10.0) + CanvasElement(1.0, 2.0, "red", "black")

你想要这样的东西吗?

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)

如果我理解正确,您不希望 CanvasElement 有默认值,并且您希望能够通过仅定义 radius 和可能的其他属性来创建 Circle CanvasElement 有。