[英]Having an abstract class that defines a primary constructor variable with a default value, how can we set that immutable value from a subclass
Given an abstract class: 给定一个抽象类:
abstract class SuperClass(val someVal: String = "defaultValue") : SomeSuperClass
I want the implementing subclass to have two constructors, one that wouldn't set someVal
, thus relying on the "defaultValue"
, another one that sets a different someVal
, that is to say, val sc = SubClass()
and val sc2 = SubClass("anotherVal")
我希望实现子类有两个构造函数,一个不会设置
someVal
,因此依赖于"defaultValue"
,另一个则设置一个不同的someVal
,即val sc = SubClass()
和val sc2 = SubClass("anotherVal")
I have tryied with: 我尝试过:
class SubClass() : SuperClass() {
constructor(someVal: String) : this(someVal)
But the compiler complains: 但是编译器抱怨:
Error:(5, 37) Kotlin: There's a cycle in the delegation calls chain
How can I implement it keeping someVal
immutable? 我如何实现它使
someVal
不可变? A solution like the following is not valid since it would be mutable: 如下所示的解决方案无效,因为它是可变的:
abstract class SuperClass(var someVal: String = "defaultValue") : SomeSuperClass
class SubClass() : SuperClass() {
constructor(someVal: String) : this() {
super.someVal = someVal
}
}
If you omit the primary constructor you can do this: 如果省略主要构造函数,则可以执行以下操作:
class SubClass : SuperClass {
constructor(someVal: String): super(someVal)
constructor(): super()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.