Created
April 30, 2025 10:39
-
-
Save valarpirai/49c51f473ab16c547db6801ed2afb31c to your computer and use it in GitHub Desktop.
Kotlin DSL Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HTML { | |
private var head: Head? = null | |
private var body: Body? = null | |
fun head(init: Head.() -> Unit): Head { | |
val head = Head() | |
head.init() | |
this.head = head | |
return head | |
} | |
fun body(init: Body.() -> Unit): Body { | |
val body = Body() | |
body.init() | |
this.body = body | |
return body | |
} | |
override fun toString(): String { | |
return "<html>${head ?: ""}${body ?: ""}</html>" | |
} | |
} | |
class Head { | |
var title: String = "" | |
fun title(text: String) { | |
this.title = "<title>$text</title>" | |
} | |
override fun toString(): String { | |
return "<head>$title</head>" | |
} | |
} | |
class Body { | |
var content: String = "" | |
fun p(text: String) { | |
content += "<p>$text</p>" | |
} | |
override fun toString(): String { | |
return "<body>$content</body>" | |
} | |
} | |
fun html(init: HTML.() -> Unit): HTML { | |
val html = HTML() | |
html.init() | |
return html | |
} | |
fun main() { | |
val myHtml = html { | |
head { | |
title("My Webpage") | |
} | |
body { | |
p("Hello, world!") | |
p("This is a Kotlin DSL example.") | |
} | |
} | |
println(myHtml) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment