For example, we have this parent:

open class Parent(val id: Int, val name: String?) {
    constructor() : this(-1, null)
}

And a child, which must have both a two-param constructor and an empty constructor, like the parent:

class Child(id: Int, name: String?) : Parent(id, name) {
    constructor() : super() // syntax error
}

子构造函数如何使用其父构造函数的二级构造函数?

I am aware that I can implement a child constructor passing in the same values as the parent, but this not only seems redundant but also often times my childs have extra parameters for its primary constructor, but don't require intermediary constructors (constructors with params that don't include all the extra params). Here's an example child implementing it that way, in case I wasn't clear:

class Child(id: Int, name: String?) : Parent(id, name) {
    constructor() : this(-1, null) // no syntax error, but redundant
}

推荐答案

实现这一点的最好方法是imho为您的构造函数使用default parameters.

class Child(id: Int = -1, name: String? = null) : Parent(id, name)

Depending on how much influence you've got on the Parent class, maybe even

class Parent(val id: Int = -1, val name: String? = null)

This has one "drawback", though: you'll technically get three different constructors. But I can't see how this could be a problem, since you have to handle the id=-1 and name=null cases anyway.

Additionally, I don't think your solution

class Child(id: Int, name: String?) : Parent(id, name) {
    constructor() : this(-1, null) 
}

is bad, or "redundant" in any way - on the contrary: it's highly expressive and explicit, so the reader knows exactly what your intention was.

Kotlin相关问答推荐

如何在Kotlin中反射多个对象以查找特定类型的属性

Kotlin是否针对范围和进度优化sum()?

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

T和T有什么区别:任何>

Kotlin 协程:flatMapLatest 什么都不发出

mutableStateOf 和 mutableStateListOf 有什么区别?

为什么记得不将 StateFlow 转换为特定类型?

Kotlin 数据类中的大量参数

Kotlin 使用委托进行隐式覆盖

如何使用 Either monad 并避免嵌套 flatMap

Picasso 回调

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

模拟异常 - 没有找到答案

Kotlin 语言是如何用 Kotlin 编写的?

在kotlin中,如何模拟封装回调函数?

如何为kotlin异常生成SerialVersionId?

Kotlin 警告:Conditional branch result of type ... is implicity cast of Any?

Kotlin - computed var 属性的用处?

Kotlin 错误:public function exposes its 'public/*package*/' return type argument

Kotlin:访问 when 语句的参数