In the following case:
class Example {
val ok = false
val def: ()-> Unit = {
if (ok) def()// Variable 'def' must be initialized
}
}
Compiler complains: Variable 'def' must be initialized
There are some opened issues for that and similar cases: KT-10350, KT-13727, KT-13805…
All are marked as ‘by design’. But i was just wondering what considerations that ‘design’ was based on.
Lambda ‘val’ declaration doesn’t imply that it’s invoked immediately. Ergo it can’t be occurred in uninitialized state. And besides that simple workaround does the trick. That leads to the same result (or error if any, that appeared to be by design too).
class Example {
val ok = false
val def: ()-> Unit = {
if (ok) execDef()
}
fun execDef(): Unit = def()
}