-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
73: Practice Exercise: Building a Simple DSL for HTML Generation
How do I actually get that "nested" look where tags sit inside other tags?
If you've looked at the code for other DSLs, you've probably seen this pattern and wondered where the magic happens. The "secret sauce" is the function literal with receiver. Instead of just passing a lambda like () -> Unit, we pass Element.() -> Unit.
This tells Kotlin: "Inside this block of code, the keyword this refers to an instance of Element." It essentially moves the scope of the lambda inside the class, allowing you to call member functions of that class without any qualifiers. I've found that this is the single biggest "aha!" moment when learning DSLs.
class Element(val name: String) {
val children = mutableListOf<Element>()
// This is the key: 'init' is a function literal with receiver
fun element(name: String, init: Element.() -> Unit) {
val child = Element(name)
child.init() // Execute the lambda in the context of the child
children.add(child)
}
}
// Usage
val root = Element("html")
root.element("body") {
// I'm now inside the 'body' Element instance
element("p") {
// I'm now inside the 'p' Element instance
}
}
How should I handle HTML attributes without making the function calls ugly?
You don't want to pass a massive Map of attributes every time you create a tag. That ruins the "clean" feeling of a DSL. The most elegant way to handle this is by using optional named arguments in your builder functions. It keeps the common cases short but allows for specificity when you need it.
In a real production environment, I might use a more complex attribute builder, but for a simple HTML generator, named arguments are usually plenty. Check out how I'd handle a div with a CSS class here:
class Element(val name: String, val attributes: Map<String, String> = emptyMap()) {
// ... rest of the class
}
fun Element.div(classes: String? = null, id: String? = null, init: Element.() -> Unit) {
val attrs = mutableMapOf<String, String>()
if (classes != null) attrs["class"] = classes
if (id != null) attrs["id"] = id
// Logic to create the element with these attributes
element("div", attrs, init)
}
// Now it looks like this:
div(classes = "container", id = "main-content") {
// nested content
}
How do I actually turn this object tree into a real HTML string?
Building the tree is the easy part; rendering it is where you have to be careful about indentation and closing tags. I recommend using a StringBuilder and a recursive function. You basically walk down the tree, append the opening tag, visit the children, and then append the closing tag.
Don't forget to handle the indentation. If you just slap the tags together, your generated HTML will be one giant, unreadable line. I usually pass a depth integer through the recursion to handle the leading spaces.
fun Element.render(depth: Int = 0): String {
val indent = " ".repeat(depth)
val attrs = attributes.entries.joinToString(" ") { " ${it.key}=\"${it.value}\"" }
val sb = StringBuilder()
sb.append("${indent}<${name}${attrs}>\n")
children.forEach { child ->
sb.append(child.render(depth + 1))
}
sb.append("${indent}</${name}>\n")
return sb.toString()
}
📋 Practical Task
Exercise: Build a Developer Portfolio Page Generator
Your task is to expand the HTML DSL concepts we just discussed to create a specialized "Portfolio Generator." Instead of generic element() calls, you need to implement a type-safe DSL that specifically supports the following tags: html, body, h1, div, p, and a (for links).
Requirements:
- Implement a
render()method that produces a properly indented HTML string. - The
atag must accept ahrefattribute as a named argument. - The
divtag must accept aclassesattribute as a named argument. - Create a main function that uses your DSL to generate a portfolio page containing:
- An
h1with your name. - A
divwith the class "projects" containing at least twoptags, each with anatag linking to a project.
- An
There are no comments for now.