Consider the following Kotlin code that uses extension functions to build a simple DSL for HTML-like tags. What will be printed when this code runs?
class Tag(val name: String) { private val children = mutableListOf<Tag>() fun tag(name: String, init: Tag.() -> Unit) { val t = Tag(name) t.init() children.add(t) } override fun toString(): String { val inner = children.joinToString("") { it.toString() } return "<$name>$inner</$name>" } } fun html(init: Tag.() -> Unit): Tag { val root = Tag("html") root.init() return root } fun main() { val result = html { tag("body") { tag("p") {} } } println(result) }
Look at how the tag function adds children inside the current tag.
The tag function creates a new Tag, initializes it, and adds it as a child to the current Tag. The toString method recursively builds the string representation. So the output nests the tags correctly.
In Kotlin, what feature primarily enables the creation of DSLs using extension functions?
Think about how lambdas can be called with a receiver object.
Higher-order functions that take lambdas with receivers allow you to write code blocks that look like they belong to a specific type, enabling DSL style syntax.
Examine the Kotlin DSL code below. It throws a NullPointerException at runtime. What is the cause?
class Builder { var text: String? = null fun build(): String { return text!!.toUpperCase() } } fun buildString(init: Builder.() -> Unit): String { val builder = Builder() builder.init() return builder.build() } fun main() { val result = buildString { // text is not set here } println(result) }
Check the value of 'text' before calling toUpperCase().
The 'text' property is null because it was never assigned a value inside the lambda. Using '!!' on a null value causes a NullPointerException.
Which of the following Kotlin code snippets correctly defines an extension function named section for a class Document that takes a lambda with receiver?
Remember the syntax for extension functions with lambda receivers.
Option C correctly defines an extension function on Document that takes a lambda with receiver Document and calls it.
Given the Kotlin DSL code below, how many Tag instances are created in total?
class Tag(val name: String) { val children = mutableListOf<Tag>() fun tag(name: String, init: Tag.() -> Unit = {}) { val t = Tag(name) t.init() children.add(t) } } fun main() { val root = Tag("root") root.tag("a") { tag("b") { tag("c") } tag("d") } root.tag("e") }
Count the root and all nested tags created by each tag call.
The root tag plus tags 'a', 'b', 'c', 'd', and 'e' are created, totaling 6 Tag instances.