简体   繁体   English

有一个抽象类定义了带有默认值的主构造函数变量,我们如何从子类中设置该不可变值

[英]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.

相关问题 覆盖主要构造函数的开放值 - Override open value from primary constructor 如何将在主构造函数中接收的列表转换为MutableList,以便我们可以将类委托给MutableList - How to cast the List received in the primary constructor to MutableList so that we can delegate the class to MutableList 我们可以在 Kotlin 中一次在数据 class 主构造函数中声明多少个变量? - How many variables we can declare in data class primary constructor at a time in Kotlin? 如何设置数据 class 的默认值 - How to set default value for data class 更改继承自具有不可变值的密封 class 的 class 中的可变值 - Changing a mutable value in a class inheriting from a sealed class with an immutable value kotlin,我们如何在使用参数传递给它的另一个类中更改Actual变量的值? - kotlin,How value of Actual variable we can change in another class to which it passed using parameter? 如何在 BehaviourSubject 中设置默认值 - How to set default value in BehaviourSubject kotlin 类构造函数参数的默认值类型是什么? - what is default value type of kotlin class constructor parameter? 如何在 Kotlin 中设置数组参数的默认值? - How can you set the default value for array parameters in Kotlin? 在 Kotlin 的超类构造函数中使用抽象值 - Use an abstract value in a superclass constructor in Kotlin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM