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

前端 未结 3 1953
广开言路
广开言路 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:40

    I'm pretty sure you can achieve the same results in a more readable and clear way using something like this:

    fun  selfReferenced(initializer: () -> T) = initializer.invoke()
    operator fun T.getValue(any: Any?, property: KProperty<*>) = this
    

    and later use

    val valueName: ValueType by selfReferenced{
        //here you can create and use the valueName object
    }
    

    Using as example your quoted question https://stackoverflow.com/a/35050722/2196460 you can do this:

    val textToSpeech:TextToSpeech by selfReferenced {
    TextToSpeech(
            App.instance,
            TextToSpeech.OnInitListener { status ->
                if (status == TextToSpeech.SUCCESS) {
                    textToSpeech.setLanguage(Locale.UK)
                }
            })
        }
    

    Inside the selfReferenced block you can use the outer object with no restrictions. The only thing you should take care of, is declaring the type explicitly to avoid recursive type checking issues.

提交回复
热议问题