dirk.dittert
01/26/2022, 3:27 PMinterface Base {
val number: Int
}
class SomeClass: Base {
override var number: Int
private set
init {
number = 42
}
}
This results in an error: Property number
must be initialized. I did not expect this as the documentation says that the code in the init block effectively becomes part of the primary constructor.
There seems to be a workaround by changing the init
block to:
constructor() {
number = 42
}
But that's something inspections don't like so much (secondary constructor should be converted to primary constructor).
Is this intended behaviour?Matteo Mirk
01/26/2022, 3:51 PMdirk.dittert
01/26/2022, 4:20 PMBase
and that provides only read only access. Internally, there can be setters for properties as well (as in my example here)Matteo Mirk
01/26/2022, 4:23 PMdirk.dittert
01/26/2022, 4:24 PMval
(in combination with an init
block).Matteo Mirk
01/26/2022, 4:27 PMdirk.dittert
01/26/2022, 4:38 PMephemient
01/27/2022, 3:47 AMoverride var number: Int = 42
private set
is it not possible to initialize normally?dirk.dittert
01/31/2022, 9:08 AMephemient
01/31/2022, 9:16 AMoverride var number: Int = 0
private set
init {
number = 42
}
final override var number: Int
private set
init {
number = 42
}
override var number: Int = 42
initializes the field directly), or the setter must not be overridable (as a subclass could then observe the uninitialized state)dirk.dittert
01/31/2022, 10:38 AMinit
block.ephemient
01/31/2022, 10:51 AM