Skip to content

Commit 731899f

Browse files
authored
update: introduce information about DslMarker with function types (#4679)
* update: Introduce information about DslMarker with function types * implementing comments * updating based on review comments from TWr review
1 parent 847295f commit 731899f

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

docs/topics/type-safe-builders.md

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,40 @@ html {
242242
}
243243
```
244244

245-
## Full definition of the com.example.html package
245+
You can also apply the `@DslMarker` annotation directly to [function types](lambdas.md#function-types).
246+
Simply annotate the `@DslMarker` annotation with `@Target(AnnotationTarget.TYPE)`:
247+
248+
```kotlin
249+
@Target(AnnotationTarget.TYPE)
250+
@DslMarker
251+
annotation class HtmlTagMarker
252+
```
253+
254+
As a result, the `@DslMarker` annotation can be applied to function types, most commonly to lambdas with receivers. For example:
255+
256+
```kotlin
257+
fun html(init: @HtmlTagMarker HTML.() -> Unit): HTML { ... }
258+
259+
fun HTML.head(init: @HtmlTagMarker Head.() -> Unit): Head { ... }
260+
261+
fun Head.title(init: @HtmlTagMarker Title.() -> Unit): Title { ... }
262+
```
263+
264+
When you call these functions, the `@DslMarker` annotation restricts access to outer receivers in the body of a lambda marked with it unless you specify them explicitly:
265+
266+
```kotlin
267+
html {
268+
head {
269+
title {
270+
// Access to title, head or other functions of outer receivers is restricted here.
271+
}
272+
}
273+
}
274+
```
275+
276+
Only the nearest receiver's members and extensions are accessible within a lambda, preventing unintended interactions between nested scopes.
277+
278+
### Full definition of the com.example.html package
246279

247280
This is how the package `com.example.html` is defined (only the elements used in the example above).
248281
It builds an HTML tree. It makes heavy use of [extension functions](extensions.md) and
@@ -345,4 +378,3 @@ fun html(init: HTML.() -> Unit): HTML {
345378
return html
346379
}
347380
```
348-

0 commit comments

Comments
 (0)