Lambda 'val' with recursive call


#1

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

#2

The issues you mentioned are not closed with “As Designed”. We recognise the use case, but it seems like a rather special case with few application, so it’s not a high-priority thing ATM


#3

Hello. Is it still very minor? While implementing animating views I often have to define Runnables which recursively post theirselves to a message queue. Due to the problem described in this discussion I have to create an anonymous function that call itself. That looks strange. Maybe I’m doing something wrong?


#4

Thanks for sharing your use case. To have it logged in the issue tracker, could you post a comment under this issue: https://youtrack.jetbrains.com/issue/KT-10350 ? Also feel free to vote for it