Kotlin DSL Patterns
Use when domain-specific language design in Kotlin using type-safe builders, infix functions, operator overloading, lambdas with receivers, and patterns for creating expressive, readable DSLs for configuration and domain modeling.
What this skill does
# Kotlin DSL Patterns
## Introduction
Kotlin's language features enable creation of expressive domain-specific
languages (DSLs) that feel like natural extensions of the language itself. DSLs
improve code readability, reduce boilerplate, and provide type-safe APIs for
configuration, builders, and domain modeling.
Key features supporting DSL design include lambdas with receivers, extension
functions, infix notation, operator overloading, and scope control. These
features combine to create fluent, intuitive APIs that express domain concepts
clearly without sacrificing type safety or IDE support.
This skill covers type-safe builders, lambda receivers, infix functions,
operator overloading, and practical patterns for designing maintainable DSLs in
Android, testing, and configuration contexts.
## Type-Safe Builders
Type-safe builders use lambdas with receivers to create hierarchical structures
with compile-time validation and IDE support.
```kotlin
// HTML DSL example
class HTML {
private val elements = mutableListOf<Element>()
fun head(init: Head.() -> Unit) {
val head = Head()
head.init()
elements.add(head)
}
fun body(init: Body.() -> Unit) {
val body = Body()
body.init()
elements.add(body)
}
override fun toString(): String {
return "<html>\n${elements.joinToString("\n")}\n</html>"
}
}
abstract class Element(val name: String) {
private val children = mutableListOf<Element>()
protected fun <T : Element> initElement(element: T, init: T.() -> Unit): T {
element.init()
children.add(element)
return element
}
override fun toString(): String {
return if (children.isEmpty()) {
"<$name/>"
} else {
"<$name>\n${children.joinToString("\n")}\n</$name>"
}
}
}
class Head : Element("head") {
fun title(text: String) {
initElement(Title()) { this.text = text }
}
}
class Title : Element("title") {
var text: String = ""
override fun toString() = "<title>$text</title>"
}
class Body : Element("body") {
fun h1(text: String) {
initElement(H1()) { this.text = text }
}
fun p(text: String) {
initElement(P()) { this.text = text }
}
fun div(cssClass: String = "", init: Div.() -> Unit) {
initElement(Div(cssClass), init)
}
}
class H1 : Element("h1") {
var text: String = ""
override fun toString() = "<h1>$text</h1>"
}
class P : Element("p") {
var text: String = ""
override fun toString() = "<p>$text</p>"
}
class Div(private val cssClass: String = "") : Element("div") {
fun p(text: String) {
initElement(P()) { this.text = text }
}
override fun toString(): String {
val classAttr = if (cssClass.isNotEmpty()) " class=\"$cssClass\"" else ""
return "<div$classAttr>...</div>"
}
}
// Using the HTML DSL
fun buildPage() = html {
head {
title("My Page")
}
body {
h1("Welcome")
p("This is a paragraph")
div("container") {
p("Nested paragraph")
}
}
}
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
// Configuration DSL
class ServerConfig {
var port: Int = 8080
var host: String = "localhost"
val routes = mutableListOf<Route>()
fun route(path: String, init: Route.() -> Unit) {
val route = Route(path)
route.init()
routes.add(route)
}
}
class Route(val path: String) {
var method: String = "GET"
var handler: (Request) -> Response = { Response(200, "OK") }
fun get(handler: (Request) -> Response) {
this.method = "GET"
this.handler = handler
}
fun post(handler: (Request) -> Response) {
this.method = "POST"
this.handler = handler
}
}
data class Request(val path: String, val body: String = "")
data class Response(val status: Int, val body: String)
fun server(init: ServerConfig.() -> Unit): ServerConfig {
val config = ServerConfig()
config.init()
return config
}
// Using configuration DSL
val config = server {
port = 9000
host = "0.0.0.0"
route("/api/users") {
get { request ->
Response(200, "User list")
}
}
route("/api/posts") {
post { request ->
Response(201, "Post created")
}
}
}
```
Type-safe builders provide IDE autocompletion and compile-time validation while
creating readable, hierarchical structures.
## Lambdas with Receivers
Lambdas with receivers enable DSL functions to access receiver properties and
methods directly, creating implicit context for cleaner APIs.
```kotlin
// Lambda with receiver basics
fun buildString(action: StringBuilder.() -> Unit): String {
val builder = StringBuilder()
builder.action()
return builder.toString()
}
val result = buildString {
append("Hello")
append(" ")
append("World")
}
// Extension functions as DSL builders
class Query {
private val conditions = mutableListOf<String>()
fun where(condition: String) {
conditions.add(condition)
}
fun build(): String {
return "SELECT * WHERE ${conditions.joinToString(" AND ")}"
}
}
fun query(init: Query.() -> Unit): String {
val query = Query()
query.init()
return query.build()
}
val sql = query {
where("age > 18")
where("status = 'active'")
}
// Scoped builders
class TestSuite(val name: String) {
private val tests = mutableListOf<Test>()
fun test(name: String, block: TestContext.() -> Unit) {
val context = TestContext()
context.block()
tests.add(Test(name, context))
}
fun run() {
println("Running suite: $name")
tests.forEach { it.run() }
}
}
class TestContext {
val assertions = mutableListOf<() -> Unit>()
fun assertEquals(expected: Any, actual: Any) {
assertions.add {
if (expected != actual) {
throw AssertionError("Expected $expected but got $actual")
}
}
}
}
class Test(val name: String, val context: TestContext) {
fun run() {
println(" Test: $name")
context.assertions.forEach { it() }
}
}
fun suite(name: String, init: TestSuite.() -> Unit): TestSuite {
val suite = TestSuite(name)
suite.init()
return suite
}
// Using test DSL
val testSuite = suite("Math Tests") {
test("addition") {
assertEquals(4, 2 + 2)
assertEquals(0, 1 - 1)
}
test("multiplication") {
assertEquals(6, 2 * 3)
}
}
// Apply and also for DSL chaining
data class Person(
var name: String = "",
var age: Int = 0,
var email: String = ""
)
fun createPerson() = Person().apply {
name = "Alice"
age = 30
email = "[email protected]"
}
// With for scoped access
fun processConfig(config: ServerConfig) {
with(config) {
println("Server on $host:$port")
routes.forEach { route ->
println(" ${route.method} ${route.path}")
}
}
}
```
Lambdas with receivers enable accessing receiver members without explicit
qualifiers, creating natural, context-aware DSL syntax.
## Infix Functions and Operators
Infix functions and operator overloading enable natural mathematical and logical
expressions in DSLs, improving readability for domain concepts.
```kotlin
// Infix functions for fluent API
infix fun String.shouldEqual(expected: String) {
if (this != expected) {
throw AssertionError("Expected '$expected' but got '$this'")
}
}
"hello" shouldEqual "hello"
// Time duration DSL with infix
class Duration(val milliseconds: Long) {
operator fun plus(other: Duration) =
Duration(milliseconds + other.milliseconds)
override fun toString() = "${milliseconds}ms"
}
infix fun Int.seconds(unit: Unit) = Duration(this * 1000L)
infix fun Int.minutes(unit: Unit) = Duration(this Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.