Consider this Kotlin DSL snippet that builds a simple HTML-like structure. What will be printed?
fun html(block: Html.() -> Unit): Html { val html = Html() html.block() return html } class Html { private val children = mutableListOf<String>() fun body(block: Body.() -> Unit) { val body = Body() body.block() children.add(body.toString()) } override fun toString() = "<html>" + children.joinToString() + "</html>" } class Body { private val children = mutableListOf<String>() fun p(text: String) { children.add("<p>$text</p>") } override fun toString() = "<body>" + children.joinToString() + "</body>" } fun main() { val result = html { body { p("Hello, DSL!") } } println(result) }
Look at how the toString() methods build the string with tags.
The DSL builds nested HTML tags by calling toString() on each part. The body contains a paragraph p tag with the text. So the output is a full HTML string with nested tags.
Which of the following best explains why Domain Specific Languages (DSLs) improve readability in code?
Think about how DSLs relate to the problem they solve.
DSLs use language and structure that matches the problem domain, so the code reads like natural instructions related to that domain. This makes it easier to read and maintain.
What error will this Kotlin DSL code produce when run?
fun html(block: Html.() -> Unit): Html { val html = Html() html.block() return html } class Html { private val children = mutableListOf<String>() fun body(block: Body.() -> Unit) { val body = Body() block(body) children.add(body.toString()) } override fun toString() = "<html>" + children.joinToString() + "</html>" } class Body { private val children = mutableListOf<String>() fun p(text: String) { children.add("<p>$text</p>") } override fun toString() = "<body>" + children.joinToString() + "</body>" } fun main() { val result = html { body { p("Hello, DSL!") } } println(result) }
Check how the lambda is called inside body function.
The body function expects a lambda with receiver Body.() -> Unit, but calls it as block(body) which is a regular function call with parameter. This causes a type mismatch error.
Which option correctly defines a Kotlin DSL to build a nested list of items?
Check how build() is called and how result is printed.
Option B correctly calls build() as a function and prints the resulting list. Option B misses parentheses on build, C tries to print toString property instead of calling it, and D tries to call result() which is a list, not a function.
Imagine you are writing configuration code for a web server. Which Kotlin DSL style snippet improves readability the most?
Think about which style reads like natural instructions and groups related settings.
Option A uses a Kotlin DSL style with nested blocks and property assignments that read like natural language. It groups SSL settings inside the ssl block, making it clear and easy to read. Other options use method calls or flat configurations that are less readable.