Override var requires initialization in assignment

I don’t understand, why this code doesn’t compile with message Property must be initialized or be abstract:

interface A {
    var num: Int
}

class AImpl : A {
    override var num: Int
    
    init {
        // some calculations
        num = 123
    }
}

The same code works if num is declared as val, or if num is initialized in assignment. I can create some factory method or initialize it with kotlin.run { }, but both options are quite ugly. So why this code cannot be compiled?

2 Likes

Seems like a bug to me.

That’s not a bug.
You can read num in the “some calculations” part of the code. And num must have a value there.

With val it works because its know that there is a single initialization that has not been hit yet. (and then you get an error only if you actually try to read it).

This code compiles fine if you replace the init block by a secondary constructor, if this option is possible go with it.

If the above advice doesn’t work, you can make num a lateinit var.