gpt4 book ai didi

inheritance - Kotlin:子构造函数如何使用其父构造函数的辅助构造函数?

转载 作者:IT老高 更新时间:2023-10-28 13:46:51 26 4
gpt4 key购买 nike

例如,我们有这个父级:

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

还有一个 child ,它必须同时有一个双参数构造函数和一个空构造函数,就像父级一样:

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

子构造器如何使用其父构造器的辅助构造器?

我知道我可以实现一个子构造函数,传递与父构造函数相同的值,但这不仅看起来是多余的,而且我的 child 经常为其主构造函数有额外的参数,但不需要中间构造函数(具有不包含所有额外参数的参数的构造函数)。这是一个以这种方式实现它的示例 child ,以防我不清楚:

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

最佳答案

实现这一点的最佳方法是恕我直言,为您的构造函数使用 默认参数

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

取决于您对 Parent 类的影响程度,甚至可能

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

不过,这有一个“缺点”:从技术上讲,您将获得三个不同的构造函数。但我看不出这怎么会是个问题,因为无论如何你都必须处理 id=-1name=null 的情况。

另外,我不认为你的解决方案

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

在任何方面都不好,或“多余” - 相反:它具有高度的表现力和明确性,因此读者确切地知道您的意图是什么。

关于inheritance - Kotlin:子构造函数如何使用其父构造函数的辅助构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44772936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com