Skip to content

Fix Kotlin DSL Builder Not Working

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Fix Kotlin DSL Builder Not Working. We cover key concepts, practical examples, and best practices.

The Problem

Kotlin type-safe DSL builder functions are not resolved or produce unexpected results.

Quick Fix

Use @DslMarker

Wrong:

class HtmlDsl {
    fun head(init: HeadDsl.() -> Unit) { }
    fun body(init: BodyDsl.() -> Unit) { }
}
class HeadDsl {
    fun title(name: String) { }
}
// Implicit receivers may conflict

Output:

Ambiguity

Right:

@DslMarker
annotation class HtmlMarker

@HtmlMarker
class HtmlDsl { }
// Use @HtmlMarker on all DSL classes

Output:

DSL marker prevents implicit receiver leakage

Use receiver lambda

Wrong:

fun html(init: HtmlDsl.() -> Unit): HtmlDsl {
    val html = HtmlDsl()
    html.init()
    return html
}
html {
    head { title("Page") }
    body { }
} // DSL works

Output:

DSL works

Right:

fun html(init: HtmlDsl.() -> Unit): HtmlDsl {
    val html = HtmlDsl()
    html.init()
    return html
}
html {
    head { title("Page") }
    body { }
}

Output:

Receiver lambda provides implicit context

Limit scope with @DslMarker

Wrong:

html {
    head {
        head { } // Should not be allowed
    }
} // No restriction

Output:

Nested misuse

Right:

// @DslMarker ensures inner head() cannot call outer head()

Output:

DSL structure enforced

Prevention

  • Use @DslMarker annotation to restrict implicit receiver access
  • Use receiver lambdas (T.() -> Unit) for builder functions
  • Use context receivers for multiple receiver DSLs

Common Mistakes with dsl

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world KOTLIN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What problem does @DslMarker solve?

@DslMarker prevents accessing methods from outer receivers when inner receivers have the same method, reducing ambiguity.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro