3

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?

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

5

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")
    }
    
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • I always kinda wondered why they didn't just do *that* in that example. No real need for re-defining the unary + operator. – EpicPandaForce Mar 30 '18 at 21:58
  • 2
    @EpicPandaForce, the `+` operator in the DSL example is overloaded for the purpose of appending multiple parts within the same block. If there's a single value that you want to handle in the DSL, there's indeed no need for such things as the overloaded operator. If you want to handle multiple values in a block, you need to pass them all somewhere. – hotkey Mar 30 '18 at 22:41
  • You could also make title infix, which would remove the need for the brackets – jrtapsell Mar 30 '18 at 23:54
  • why is option 1 overhead? – Jacob Wu Aug 19 '18 at 23:06