Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to avoid function names at all in Kotlin DSL?

In Kotlin DSL example they use plus signs to implement raw content inserting:

html {
    head {
        title {+"XML encoding with Kotlin"}
    }
    // ...
}

Is it possible to define "nameless" functions in receiver to be able to write

html {
    head {
        title {"XML encoding with Kotlin"}
    }
    // ...
}

Are there any plans to do so in future versions of Kotlin?

Is there such things in languages, other than Kotlin?

like image 728
Dims Avatar asked Nov 01 '25 02:11

Dims


1 Answers

I can think of two solutions to your problem:

  1. Make the lambda with receiver return a String:

    fun title(init: Title.() -> String) {
        val t = Title().apply {
            children.add(TextElement(init()))
        }
        children.add(t)
    }
    

    You can now call the title as suggested in OP. Actually this seems to be overhead in this particular scenario though and I'd recommend the following.

  2. Create another title method that takes a String directly:

    class Head : TagWithText("head") {
        fun title(init: Title.() -> Unit) = initTag(Title(), init)
        fun title(text: String) {
            val t = Title().apply {
                children.add(TextElement(text))
            }
            children.add(t)
        }
    }
    

    Used like this:

    head {
        title("XML encoding with Kotlin")
    }
    
like image 125
s1m0nw1 Avatar answered Nov 04 '25 02:11

s1m0nw1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!