Is there a cleaner way to set a top-level variable later in code without making it a lateinit var?
07:57 27 Apr 2020

So what I want to achieve is that to have the top-level variable set some time later in the main function, but I don't want to make it a lateinit var which certainly breaks the Extension variable functionality.

For instance this code doesn't work since extension variables don't support lateinit modifier:

lateinit var Dispatchers.Konvironment: MainCoroutineDispatcher
    private set

fun main() {
    ...
    Dispatchers.Konvironment = ArbitraryMainDispatcher(Thread.currentThread()) { queue.add(it) }
    ...
}

So what I finally came up with is to use a dummy variable and implement the getter of the val variable.

val Dispatchers.Konvironment: MainCoroutineDispatcher
    get() = dispatcher

private lateinit var dispatcher: MainCoroutineDispatcher

fun main() {
    ...
    dispatcher = ArbitraryMainDispatcher(Thread.currentThread()) { queue.add(it) }
    ...
}

But it is certainly not clean way to do that. It looks ugly (ish) creating multiple variable in the top-level structure is not very clean architecture.

So is there any possible clean workarounds? Sort of like lazy initialization, by some delegates or something.

variables kotlin coding-style lazy-initialization clean-architecture