0
0
Kotlinprogramming~30 mins

Extensions for DSL building in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Simple HTML DSL with Kotlin Extensions
📖 Scenario: Imagine you want to create HTML content using Kotlin code in a neat and readable way. You will build a small DSL (Domain Specific Language) using Kotlin extensions to create HTML tags easily.
🎯 Goal: Build a Kotlin program that uses extension functions to create a simple HTML DSL. You will define tags and nest them, then print the generated HTML string.
📋 What You'll Learn
Create a class called HTML with a content property to hold the HTML string.
Create an extension function html on HTML to add the <html> tag.
Create extension functions head and body on HTML to add <head> and <body> tags.
Use lambda parameters to allow nesting tags inside each other.
Print the final HTML string.
💡 Why This Matters
🌍 Real World
Building DSLs like this helps developers write code that looks like the language they want to generate, such as HTML, SQL, or configuration files.
💼 Career
Many Kotlin developers use DSLs to simplify complex tasks, improve code clarity, and reduce errors in projects like web development, build scripts, or testing frameworks.
Progress0 / 4 steps
1
Create the HTML class to hold content
Create a class called HTML with a mutable property content of type StringBuilder initialized empty.
Kotlin
Need a hint?

Use val content = StringBuilder() inside the class to store HTML text.

2
Add an extension function html to add <html> tag
Add an extension function html on HTML that takes a lambda block: HTML.() -> Unit. Inside it, append <html> to content, call block(), then append </html>.
Kotlin
Need a hint?

Use fun HTML.html(block: HTML.() -> Unit) and call block() inside.

3
Add extension functions head and body for tags
Add extension functions head and body on HTML that take a lambda block: HTML.() -> Unit. Each should append the opening tag (<head> or <body>), call block(), then append the closing tag.
Kotlin
Need a hint?

Define head and body similarly to html, appending tags and calling block().

4
Use the DSL to build and print HTML content
Create an HTML instance called htmlPage. Call htmlPage.html with a lambda that calls head and body. Inside head, append <title>My Page</title> to content. Inside body, append <h1>Welcome</h1>. Finally, print htmlPage.content.toString().
Kotlin
Need a hint?

Use htmlPage.html { head { ... } body { ... } } and append strings inside lambdas. Then print the content.