Search code examples
kotlindelegated-properties

How to improve lazy delegate?


How i can improve this declaration:

val __name: String by lazy {
     createHTML().small {
         +name
     }
}

like as my own delegate builder html:

val __name: String by html {
    small {
        +name
    }
}

Solution

  • It seems you want a function html, wrapping lazy and returning a Lazy<T>:

    fun html(builder: Html.() -> Unit) = lazy { createHtml().builder() }
    

    (I don't know the type returned by createHtml, so I'm assuming it's called Html.)

    I'm not sure this is good design, however, since it loses the semantic value of lazy, and because it only really serves to save a few characters, but this is just my opinion.