I'm looking into Kotlin DSL for a project, and I'm wondering if there is a way to weave constraints into the DSL. I'd like these to be compilation constraints if possible, I'm aware that it's possible to throw exceptions for these cases but my ideal is compiler enforcement.
Using the HTML DSL example in the docs (https://kotlinlang.org/docs/type-safe-builders.html):
- can function ordering be enforced?
fun result() =
html {
body { // cause a compiler error, body used before head
...
}
head { ... }
- can duplicates be disallowed?
fun result() =
html {
head { ... }
head { // cause a compiler error, disallow duplicate head
...
}
body { ... }
- can existence be required?
html {
head { ... }
// Compiler error, body is required
}
Again, ideally these are compiler errors, not exceptions. Is this possible?
I tried with DslMarker but didn't find a way to get it working.
Thanks!