0

I have the following code:

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")
        }
}

And IntelliJ IDEA is suggesting converting the constructor to a primary constructor.

So how to convert this? How to init a property with a setter in a primary constructor? I have tried init blocks but it then shows an error: "Variable can not be initialized before declaration".

Shreck Ye
  • 1,591
  • 2
  • 16
  • 32

2 Answers2

2

Such a primary constructor would go in the header of the class, like this:

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

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

}

You can get this conversion done by the IDE by invoking intention actions on the warning (Alt + Enter on Windows, ⌥↩ on macOS), and choosing Convert to primary constructor.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Expanding on this: Custom getters and setters aren't supported in the primary constructor because [there wasn't/isn't a good syntax to implement the feature with](https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640/2) – Zoe Nov 26 '18 at 14:52
2

The init block must come after the variale declaration. That's what the error message is telling you:

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
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255