扩展类条件分支超值的 Kotlin 二级构造函数

ers*_*tan 3 constructor kotlin

您如何根据第四个二级构造函数中的值进行条件超级调用?为什么这不起作用?

open class SecondaryConstructors{
    constructor(i:Int)
    constructor(s:String)
}
class SecondaryExtended:SecondaryConstructors {
    constructor(i:Int):super(i)
    constructor(s:String):super(s)
    constructor():super(if(true)1 else 0)
    constructor(intOrString:Boolean):super( if(intOrString) 3 else "hey")
    // conditional branch result of int/string is implicitly cast to Any
    // error - none of the following functions can be called with the arguments supplied
}
Run Code Online (Sandbox Code Playgroud)

s1m*_*nw1 5

这将不起作用,因为if作为构造函数的参数传递的表达式没有唯一类型,除了Any,这是最常见的类型。由于没有匹配的构造函数需要Any作为参数,因此出现错误。

constructor(intOrString:Boolean):
super( if(intOrString) 3 else "hey")
Run Code Online (Sandbox Code Playgroud)

与在 Java 中一样,不可能进行有条件的超级调用。超级类型必须直接初始化,如文档所述

如果类没有主构造函数,那么每个辅助构造函数都必须使用 super 关键字初始化基类型,或者委托给 > 另一个执行此操作的构造函数。请注意,在这种情况下,不同的辅助构造函数可以调用基类型的不同构造函数