https://kotlinlang.org logo
Title
k

karelpeeters

07/11/2017, 10:27 PM
Is there a workaround for this issue?
class MyClass {
    var a: Int
    
    init {
        computeA()
    }

    private fun computeA() {
        a = 5
    }
}
The compiler complains that I have to initialize
a
, apparently it can't tell
computeA()
does initialize it.
a

asimaruk

07/11/2017, 10:30 PM
@karelpeeters use
lateinit var
modifier
👎 1
k

karelpeeters

07/11/2017, 10:32 PM
I can't believe I didn't think of that! I've been abusing
lateinit
a bit lately so I forgot it has legitimate use cases too 😒imple_smile:.
Thanks a lot @asimaruk
👌 1
d

diesieben07

07/11/2017, 10:35 PM
To be honest, this doesn't sound like a legitimate use-case for lateinit. Why not
var a = computeA()
?
👍 1
k

karelpeeters

07/11/2017, 10:36 PM
Because I computeA() will be called from a lot of other setters. Basically is the result of an expensive calculation on a couple of other variables, and I want to reduce boilerplate.
a

agrosner

07/11/2017, 10:37 PM
Use lazy
k

karelpeeters

07/11/2017, 10:38 PM
Does lazy have an invalidate method or something? I want the field to change as others change as well.
d

diesieben07

07/11/2017, 10:49 PM
Ok, Then lateinit seems fine 🙂
a

asimaruk

07/11/2017, 10:55 PM
Check your custom setters. They won't assign a new value to property. Better use
var position by Delegates.observable(position) { prop, old, new -> updateView() }
👍 1