我正在为HTML构建Kotlin DSL,以满足我的非常具体的要求(因此不使用kotlinx.html)
DIV(classes = "div1") {
+"text1"
a(href = "#0") {
+"text2"
div(classes = "div2") {
+"text3"
href = "#1"
}
div(classes = "div3") {
+"text4"
href = "#2"
}
}
hr(classes = "hr1")
span(classes = "span1") {
+"text5"
}
}
在上面的示例中,我可以在href
的任何子元素中调用a
,而不必执行[email protected] = ""
。如何限制范围,以使this
在此示例中仅为DIV
类型,并且由于href
没有DIV
属性而在调用href
时引发编译器错误?
这里是DIV
类的简化版本https://github.com/persephone-unframework/dsl/blob/master/src/main/kotlin/io/persephone/dsl/element/DIV.kt
@DslMarker
annotation class DivMarker
@DivMarker
class DIV(
classes: String? = null,
....
init: (DIV.() -> Unit)? = null
) : Tag(
tagName = "div",
selfClosing = false
) {
fun a(
classes: String? = null,
....
init: (A.() -> Unit)? = null
) = A().let {
this.children.add(it)
....
init?.invoke(it)
it
}
....
}
类似地,A类也被标记为:https://github.com/persephone-unframework/dsl/blob/master/src/main/kotlin/io/persephone/dsl/element/A.kt
@DslMarker
annotation class AMarker
@AMarker
class A(
href: String? = null,
...
init: (A.() -> Unit)? = null
) : Tag(
tagName = "a",
selfClosing = false
) {
fun div(
classes: String? = null,
init: (DIV.() -> Unit)? = null
) = DIV().let {
this.children.add(it)
....
init?.invoke(it)
it
}
....
}
任何想法,为什么@DslMarker
注释在这种情况下都不会限制范围,我该如何解决?