在 Kotlin 中覆盖多个版本的构造函数

Overriding multiple versions of constructor in Kotlin

我试图在 Kotlin 中实现 CustomView,它将以编程方式和静态方式使用。因此,我需要覆盖两个版本的构造函数。

为了以编程方式我使用版本,

class CustomView @JvmOverloads constructor(
   context: Context, 
) : View(context)

对于静态我使用版本,

class CustomView @JvmOverloads constructor(
  context: Context, 
  attrs: AttributeSet? = null,
) : View(context, attrs)

我如何更改它以覆盖相同 class 下的多个版本,然后我可以从静态视图以及以编程方式实例化?

构造函数中有一些 post,即 Kotlin secondary constructor,这对覆盖多个版本的构造函数没有帮助。

这应该以编程方式和静态方式工作:-

class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr)

以编程方式调用 :-

CustomView(context) // passing other params to constructor is not mandatory..

我创建了这段代码来重现您的问题:

Test.java:

public class Test {

    private int i ;
    private String name;

    public Test(int i) {
        this.i = i;
        name = "test";
    }

    public Test(int i, String name) {
        this.i = i;
        this.name = name;
    }
}

TestK.kt:

class TestK : Test {
    constructor(i: Int, name: String): super(i, name)
    constructor(i: Int) : super(i)
}

如您所见,我用不同的参数量重载了父构造函数。