Writing a Kotlin util function which provides self-reference in initializer

前端 未结 3 1952
广开言路
广开言路 2020-12-06 06:05

I\'m trying to generalize my hack from an answer to another question.

It should provide a way to reference a value which is not constructed yet inside its initializ

3条回答
  •  无人及你
    2020-12-06 06:46

    The best I have managed to produce while still being completely generic is this:

    class SelfReference(val initializer: SelfReference.() -> T)  {
        val self: T by lazy {
            inner ?: throw IllegalStateException("Do not use `self` until initialized.")
        }
    
        private val inner = initializer()
        operator fun invoke(): T = self
    }
    

    Adding the invoke operator lets you use it in the following way:

    val h: Holder = selfReference { Holder(0) { this().x++ } }
    

    This is the closest I got to make it look like something you would "normally" write.

    Sadly I think it is not possible to get completely rid of a explicit access to the element. Since to do that you would need a lambda parameter of type T.() -> T but then you wouldn't be able to call that parameter without an instance of Tand being T a generic there is no clean and safe way to acquire this instance.

    But maybe I'm wrong and this helps you think of a solution to the problem

提交回复
热议问题