【问题标题】:Init a property with a setter in a primary constructor in Kotlin在 Kotlin 的主构造函数中使用 setter 初始化属性
【发布时间】:2018-11-26 08:11:19
【问题描述】:

我有以下代码:

class Camera : AsyncActiveInputDevice<Image> {
    constructor(inputListener: ((Image) -> Unit)? = null) {
        this.inputListener = inputListener
    }

    override var inputListener: ((Image) -> Unit)?
        set(value) {
            field = value
            TODO("call C/Python implementation")
        }
}

IntelliJ IDEA 建议将构造函数转换为主构造函数。

那么如何转换呢?如何在主构造函数中使用 setter 初始化属性?我尝试了init 块,但随后显示错误:“变量无法在声明前初始化”。

【问题讨论】:

    标签: kotlin constructor properties primary-constructor


    【解决方案1】:

    这样的主构造函数会放在类的头部,像这样:

    class Camera(inputListener: ((Image) -> Unit)? = null) : AsyncActiveInputDevice<Image> {
    
        override var inputListener: ((Image) -> Unit)? = inputListener
            set(value) {
                field = value
                TODO("call C/Python implementation")
            }
    
    }
    

    您可以通过对警告调用意图操作(在 Windows 上为 Alt + Enter,在 macOS 上为 ⌥↩)并选择 转换为主构造函数

    【讨论】:

    【解决方案2】:

    init 块必须在变量声明之后。这就是错误消息告诉您的内容:

    class Camera(inputListener: ((Image) -> Unit)? = null): AsyncActiveInputDevice<Image> {
    
        override var inputListener: ((Image) -> Unit)? = inputListener
            set(value) {
                field = value
                TODO("call C/Python implementation")
            }
    
    
        init {
            this.inputListener = inputListener
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-11
      • 2019-10-07
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2020-06-12
      • 2017-06-13
      相关资源
      最近更新 更多